# Sum over cell array of sparse matrices error: Dimension for sparse matrix concatenation must be <= 2.

3 visualizzazioni (ultimi 30 giorni)
Xiaohan Du il 13 Nov 2017
Modificato: Koen Ruymbeek il 12 Feb 2020
Hi all,
I have a cell contains sparse matrices,
K>> a
a =
2×1 cell array
[12×12 double]
[12×12 double]
Now I'd like to sum these 2 sparse matrices into 1. I tried:
K>> sum(cat(3, a{:}), 3)
which gave me error:
Error using cat
Dimension for sparse matrix concatenation must be <= 2.
This line works for non-sparse matrices, but not for sparse matrices. Manually extract cell elements and sum them is not acceptable. Any idea how to do it? I CANNOT go back to full matrices and sum them.
Thanks!
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposte (1)

James Tursa il 13 Nov 2017
Modificato: James Tursa il 13 Nov 2017
For your particular example, of course
result = a{1} + a{2};
What are the sizes of your real problem? I.e., what are the dimensions of "a" and all of the cell elements?
##### 5 CommentiMostra 3 commenti meno recentiNascondi 3 commenti meno recenti
James Tursa il 13 Nov 2017
Modificato: James Tursa il 14 Nov 2017
MATLAB gives you that error because MATLAB does not support multi-dimensional sparse matrices. MATLAB only supports 2D matrices. So the cat across the 3rd dimension with sparse matrices fails, because you are trying to build a 3D sparse matrix which is not supported. There is an FEX submission by Matt J that you can use if you really want to:
Koen Ruymbeek il 12 Feb 2020
Modificato: Koen Ruymbeek il 12 Feb 2020
Probably it is already far too late, but for someone who has the same question:
In fact you do not need the work around with 3-dimensional sparse arrays. You can first convert the matrices in the cell to a vector, and then sum them using cat. In matlab-language, this is
n = 1000;
Ahelp = {randn(n,n), randn(n,n), randn(n,n), randn(n,n)}
Ahelp = cellfun( @(x) x(:), Ahelp, 'Uniform', false);
A = reshape( sum( cat(2, Ahelp{:}),2),n,n);

Accedi per commentare.

### Categorie

Scopri di più su Sparse Matrices in Help Center e File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by