1
votes

I would like to store an array of different sparse matrices into a single matrix, something like this:

A(:,:,1) = sparse([0 0 1; 0 1 0]);

A(:,:,2) = sparse([0 0 1; 0 0 0]);

A(:,:,3) = sparse([1 0 1; 0 0 0]);

A(:,:,4) = sparse([0 0 1; 0 1 0]);

But, I get the error:

N-dimensional indexing allowed for Full matrices only.

It seems like others have ran into this problem: https://www.mathworks.com/matlabcentral/newsreader/view_thread/276098

but the link to the "bug fix" was broken and I am not sure how to deal with this issue. I know that I could use cell arrays but I know that they are slow and I am trying to avoid them. I guess that I could also use the full() command, but I am not sure if that is the best (fastest) way.

Any ideas?

1
do you need sparse matricies? In general they are slower then normal matricies, but sometimes unavoidable due to memory constraints.user2457516
btw that link is irrelevant anyway, here is a cached copy: web.archive.org/web/20100308064805/http://www.mathworks.com/…Amro

1 Answers

2
votes

Simply put, you cannot create N-dimensional sparse arrays in MATLAB, they have to be 2D matrices.

In addition, the types supported are either double or logical only (although there are hacks to create single sparse matrices, but they are ultimately useless for any actual use).

If you want to store multiples sparse matrices, you gotta use a container type (like cell-arrays or structs).


Rant: Claiming that cell-arrays are slow is ill-founded. It doesn't matter much if you were looping over arr(:,:,i) or arr{i}, unless the goal was to perform vectorized operation on the whole ND-array in the first place (not supported for sparse arrays). So just think of a cell array as an array of pointers, and arr{i} is simply de-referencing the pointer to get to another array...