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

1 view (last 30 days)
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

Accepted Answer

Cedric
Cedric on 23 Apr 2013
Edited: Cedric on 23 Apr 2013
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

More Answers (1)

Ming
Ming on 23 Apr 2013
Edited: Ming on 23 Apr 2013
Thank you very much Cedric, you are a genius and super kind!
  1 Comment
Cedric
Cedric on 23 Apr 2013
Edited: Cedric on 23 Apr 2013
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.

Sign in to comment.

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!