How to transfer a sparse matrix into a block diagnal matrix efficiently?

2 次查看(过去 30 天)
Hi, Everyone:
Suppose I have a very large M*N sparse matrix A, where M=K*N, I need to equally split it into K N*N matrices and put all of them on the diagnal of a large matrix,i.e.:
[N*N(1) 0 0 0...0 0 0 ;
0 0 N*N(2) 0 0 ... 0 ;
0 0 . 0 0 ... 0 ;
0 0 0 0 . 0 0 ... 0 ;
0 0 0 0 0 . 0 ... 0 ;
0 0 ... 0 0 0 0 N*N(K)]'
I can't use loop because K is very big, so I tried to use:
B=mat2cell(A,N*ones(K,1),N);
C=[blkdiag(B{1:end,1})];
But I found mat2cell is still quite slow when K is very big, is there any other more efficient way to do this?
Many Thanks

采纳的回答

Cedric
Cedric 2013-4-23
编辑:Cedric 2013-4-23
I would go for something like:
% - Build example case.
K = 3 ;
N = 4 ;
A = sparse(randi(10, K*N, N)-1) ;
% - Extract rows,cols,vals, and reindex columns.
[r,c,v] = find(A) ;
c = c + floor((r-1)/N) * N ;
% - Build block diagonal version.
B = sparse(r, c, v, K*N, K*N)
With this, you have:
>> full(A)
ans =
8 9 6 6
9 4 7 3
1 8 7 9
9 1 3 0
6 4 6 4
0 9 1 3
2 7 7 7
5 9 0 7
9 6 2 1
9 0 0 4
1 8 0 4
9 9 8 6
>> full(B)
ans =
8 9 6 6 0 0 0 0 0 0 0 0
9 4 7 3 0 0 0 0 0 0 0 0
1 8 7 9 0 0 0 0 0 0 0 0
9 1 3 0 0 0 0 0 0 0 0 0
0 0 0 0 6 4 6 4 0 0 0 0
0 0 0 0 0 9 1 3 0 0 0 0
0 0 0 0 2 7 7 7 0 0 0 0
0 0 0 0 5 9 0 7 0 0 0 0
0 0 0 0 0 0 0 0 9 6 2 1
0 0 0 0 0 0 0 0 9 0 0 4
0 0 0 0 0 0 0 0 1 8 0 4
0 0 0 0 0 0 0 0 9 9 8 6

更多回答(1 个)

Ming
Ming 2013-4-23
编辑:Ming 2013-4-23
Thank you very much Cedric, you are a genius and super kind!
  1 个评论
Cedric
Cedric 2013-4-23
编辑:Cedric 2013-4-23
Thank you Ming, I'm glad it helped!
The trick with sparse matrices construction/transformation is often to work on indices rather than on matrices themselves.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Sparse Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by