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

4 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Laurent
Laurent le 18 Juil 2011
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 commentaires
Walter Roberson
Walter Roberson le 18 Juil 2011
Looks like it is possibly messier than it needs to be, but please explain what exactly how your input A is structured.
Laurent
Laurent le 19 Juil 2011
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

Connectez-vous pour commenter.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 17 Juil 2011
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 commentaires
Walter Roberson
Walter Roberson le 17 Juil 2011
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 le 20 Juil 2011
@Walter: BLKDIAG replies a sparse array if any input is sparse.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by