Sum over cell array of sparse matrices error: Dimension for sparse matrix concatenation must be <= 2.
조회 수: 5 (최근 30일)
이전 댓글 표시
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
답변 (1개)
James Tursa
2017년 11월 13일
편집: James Tursa
2017년 11월 13일
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
James Tursa
2017년 11월 13일
편집: James Tursa
2017년 11월 14일
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
2020년 2월 12일
편집: Koen Ruymbeek
2020년 2월 12일
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);
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!