Stacking diagonal matrices generated from rows of other matrix
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Distelfink
am 4 Mär. 2022
Kommentiert: Distelfink
am 4 Mär. 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 Kommentare
Akzeptierte Antwort
Stephen23
am 4 Mär. 2022
Bearbeitet: Stephen23
am 4 Mär. 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 Kommentare
Stephen23
am 4 Mär. 2022
Bearbeitet: Stephen23
am 4 Mär. 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.
Weitere Antworten (4)
Matt J
am 4 Mär. 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 Kommentare
KSSV
am 4 Mär. 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),[])'
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!