Matlab only supports sparse matrices (2D). For 3D tensors / arrays you will have to use a workaround. I can think of two:
- linear indexing
- cell arrays
Linear indexing
You can create a sparse vector as follows:
A = spalloc(500000*60*60, 1, 100);
where the last entry ( 100 ) refers to the number of nonzero elements that should ultimately be tied to A If you know this amount in advance, this makes memory usage for A more efficient. If you don’t know this beforehand, just use some number next to it, it will work anyway, but A may consume more memory at the end than necessary.
Then you can refer to the elements as if it were a three-dimensional array:
A(sub2ind(size(A), i,j,k))
where i , j and k are indices for the 1st, 2nd and 3rd dimensions, respectively.
Array Cells
Create each 2D page in a 3D tensor / array as an array of cells:
a = cellfun(@(x) spalloc(500000, 60, 100), cell(60,1), 'UniformOutput', false);
The same applies to this last entry in spalloc . Then combine in 3D like this:
A = cat(3, a{:});
then you can refer to individual elements as follows:
A{i,j,k}
where i , j and k are indices for the 1st, 2nd and 3rd dimensions, respectively.