Transforming a array of matrices into a single large matrix with these matrices on the diagonal.

조회 수: 1 (최근 30일)
Hi,
I have an array of length z with different n times m matrices. Now I would like to put all these matrices on the diagonal of some large sparse matrix. If the matrices were all identical, I would simply write:
kron(speye(z,z),A)
Unfortunately, in my case they are not. So the above doesn't really work. Is there a simple elegant way to solve my problem?
Regards, Laurent

채택된 답변

Laurent
Laurent 2011년 7월 18일
I think this does the trick:
function B = MatsDiag(A)
[ l c m ] = size(A)
B = sparse( ...
reshape(repmat(reshape(1:m*l,l,[]),c,1),[],1), ...
kron(1:m*c,ones(1,l))', ...
reshape(A(:,:),[],1), ...
m*l,m*c);
end
where I assume that A(:,:,i) is the i-th matrix with size l times c. I shortly tested it with a small number of parameter choices and it seems to work, but I guess there quite some room for optimisation left.
Regards, Laurent
  댓글 수: 2
Walter Roberson
Walter Roberson 2011년 7월 18일
Looks like it is possibly messier than it needs to be, but please explain what exactly how your input A is structured.
Laurent
Laurent 2011년 7월 19일
Consider the following code
l = 4;
c = 2;
m = 3;
A = zeros(l,c,m);
for i=1:m
for j = 1:l
for k = 1:c
A(j,k,i)=i*100+j*10+k;
end
end
end
In that case A(:,:,i) will be a 4 times 2 matrix for i=1,...,3, e.g. A is an array of length 3 of 4 times 2 matrices. If you check the output from the code above, then the entries will be of the form 'abc' where a is the matrix, b its line and c its column.
I hope this makes the structure of A a bit clearer.
As for my proposed solution, I played around with it little more and think it's working in all the cases where I need it.
Regards,
Laurent

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2011년 7월 17일
See blkdiag()
This will, I know, produce a full matrix instead of a sparse matrix, but it will at least get the elements positioned as you would like.
You might consider the less direct use of spconvert()
  댓글 수: 3
Walter Roberson
Walter Roberson 2011년 7월 17일
What does it mean to say that you have an array that contains matrices? Does it mean that your array is a cell array? If so then,
blkdiag(V{:})
Jan
Jan 2011년 7월 20일
@Walter: BLKDIAG replies a sparse array if any input is sparse.

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by