Sparse 3D Matrices in Matlab

As known, Matlab does not directly deal with 3D matrices. A workaround is using cell arrays of sparse matrices.

Suppose that you want to create a sparse matrix containing only the elements (1, 1, 1) and (1, 3, 50) and suppose that A(1, 1, 1) = 1 and A(1, 3, 10) = 54.

You can do the following:

mySp{1}  = sparse(3, 3);
mySp{10} = sparse(3, 3);
 

mySp{1}(1, 1) = 3;
mySp{10}(1, 3) = 54;

In this way,

>> mySp
 
mySp = [3x3 double]    []    []    []    []    []    []    []    []    [3x3 double]

As it can be seen, mySp is an array of 10 elements. The first and the tenth elements are sparse matrices, while the others are empty. The non-empty first and tenth sparse matrices can be recovered as

temp1 = mySp{1};

temp2 = mySp{10};

returning

>> temp1
 
temp1 =
 
(1,1)        3

and

temp2 =
 
(1,3)       54

Leave a Reply

Your email address will not be published. Required fields are marked *