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

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Laurent
Laurent il 18 Lug 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 Commenti
Walter Roberson
Walter Roberson il 18 Lug 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 il 19 Lug 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

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 17 Lug 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 Commenti
Walter Roberson
Walter Roberson il 17 Lug 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{:})

Accedi per commentare.

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by