Sparse * Sparse TTM with dense output fails on reshape
Multiplying a sparse tensor by a sparse matrix fails when the output is dense and ndims>2. MWE and comparative examples:
The bug in question: sparse T * sparse A = dense Y
A = sprand(5,10,0.9);
T = sptenrand([2,5,3],0.9);
mode = 2;
Y = ttm(T,A',mode);
Sparse T * sparse A = sparse Y
A = sprand(5,10,0.2);
T = sptenrand([2,5,3],0.1);
mode = 2;
Y = ttm(T,A',mode);
Dense but sparse T * dense A = dense Y (not clear why this one works)
A = rand(5,10);
T = sptenrand([2,5,3],0.9);
mode = 2;
Y = ttm(T,A',mode);
sparse T * dense A = sparse Y
A = rand(5,10);
T = sptenrand([2,5,3],0.1);
mode = 2;
Y = ttm(T,A',mode);
Dense T * sparse A = dense Y
A = rand(5,10,0.1);
T = tenrand([2,5,3]);
mode = 2;
Y = ttm(T,A',mode);
Dense T * dense but sparse A = dense Y
A = rand(5,10,0.9);
T = tenrand([2,5,3]);
mode = 2;
Y = ttm(T,A',mode);
Dense T * dense A = dense Y
A = rand(5,10);
T = tenrand([2,5,3]);
mode = 2;
Y = ttm(T,A',mode);
EXPLANATION The bug is due to attempting to reshape a sparse Nd in tensor(.) on the last line of ttm. When spttm is run, it does the multiply X = double(sptenmat(T,2))M'. If nnz(X) > 0.5prod(size(X)), then it attempts to cast the output to a dense tensor. To do this, it constructs a tenmat on X, and then tries to make it a tensor. Note that the tenmat.data passed into the call to tensor is still sparse. To make it a tensor, a reshape is called on tenmat.data. If the number of dimensions ndims(ttm(T,A',mode)) > 2, this reshape fails because the output would be a sparse nDarray
a simple but inelegant workaround is to either cast Y into a full matrix, or to cast the output twice, as the constructors sptensor->tensor conversion does work. I attempted to implement logic for this directly in tensor.m, but the issue is that 1) construction of sparse nD arrays is not supported in base matlab and 2) preserving the sparse data type of the input was not easily possible if you cast it to full.