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

5 ビュー (過去 30 日間)
Xiaohan Du
Xiaohan Du 2017 年 11 月 13 日
編集済み: Koen Ruymbeek 2020 年 2 月 12 日
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!

回答 (1 件)

James Tursa
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
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
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);

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeSparse Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by