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

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일

0 개 추천

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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Risk Management Toolbox에 대해 자세히 알아보기

제품

질문:

2013년 4월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by