MATLAB: How to transfer a sparse matrix into a block diagnal matrix efficiently

block diagnallarge sparse matrixMATLAB

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

Best Answer

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