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

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

 채택된 답변

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

Looks like it is possibly messier than it needs to be, but please explain what exactly how your input A is structured.
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개)

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

If I understand the documentation for blkdiag() correctly, you have to specify explicitly all the matrices, e.g.
blkdiag(A,B,C,D)
returns the desired result, but if I have an array V that contains the matrices A, B, C and D, then
blkdiag(V)
will result in an error. Since I'm trying to write a function, I can't really state all the matrices explicitly. Correct me if I'm wrong on this subject.
Regards,
Laurent
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{:})
@Walter: BLKDIAG replies a sparse array if any input is sparse.

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

태그

질문:

2011년 7월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by