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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by