Sum over cell array of sparse matrices error: Dimension for sparse matrix concatenation must be <= 2.
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
James Tursa
le 13 Nov 2017
Modifié(e) : James Tursa
le 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 commentaires
James Tursa
le 13 Nov 2017
Modifié(e) : James Tursa
le 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
le 12 Fév 2020
Modifié(e) : Koen Ruymbeek
le 12 Fév 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);
Voir également
Catégories
En savoir plus sur Sparse Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!