Stacking diagonal matrices generated from rows of other matrix
13 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Distelfink
el 4 de Mzo. de 2022
Comentada: Distelfink
el 4 de Mzo. de 2022
Dear matlab forum,
I am pretty new to matlab and would like to do the following. Consider the matrix C.
C=magic(4)
From the second to fourth entries of the rows of C, I want to create diagonal matrices, which I want to stack to generate my target matrix D. I could do this with the following loop:
D=[];
for i=1:4
A=diag(C(i,2:4));
D=[D;A];
end
D
How can I do this operation efficiently, i.e. in vectorized form and without using a loop?
Thanks a lot in advance!
0 comentarios
Respuesta aceptada
Stephen23
el 4 de Mzo. de 2022
Editada: Stephen23
el 4 de Mzo. de 2022
The simplest approach is probably just to use an intermediate cell array:
N = 4;
M = magic(N);
C = cell(1,N);
for k = 1:N
C{k} = diag(M(k,2:4));
end
A = vertcat(C{:})
2 comentarios
Stephen23
el 4 de Mzo. de 2022
Editada: Stephen23
el 4 de Mzo. de 2022
"Still, is there a way to circumvent the for loop?"
Possibly, with some effort and fiddling around with indices or something like that.
"...looking for an efficient way "
Loops are efficient. Why does this incorrect rumour persist that loops are not efficient?
There is absolutely no reason to believe that vectorized code of this task will be faster or use less memory: in many instances vectorized code is slower because it requires larger intermediate arrays. Not only that, but a fully vectorized solution would considerably obfuscate the intent of your code, making maintaining the code much slower (total time cost includes run time, write time, debugging time, maintenance time).
Most likely you have already spent more time on this thread than you could save making the code faster.
I would use the loop with a cell array and VERTCAT: it is efficient and its intent is clear.
Más respuestas (4)
Matt J
el 4 de Mzo. de 2022
C=magic(4)
c=C(:,2:4);
[m,n]=size(c);
D=repmat(eye(n),m,1);
D(logical(D))=c(:)
Matt J
el 4 de Mzo. de 2022
C=magic(4)
c=C(:,2:4);
[m,n]=size(c); p=m*n;
D=zeros(p,n);
D( (1:n:p)'+ (0:n-1)*(p+1) )=c(:)
0 comentarios
KSSV
el 4 de Mzo. de 2022
This would be better than given code:
C=magic(4) ;
D=zeros(3,3,4);
for i=1:4
D(:,:,i)=diag(C(i,2:4));
end
D = reshape(permute(D,[2,1,3]),size(D,2),[])'
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!