Stacking diagonal matrices generated from rows of other matrix
Show older comments
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!
Accepted Answer
More Answers (4)
C=magic(4)
c=C(:,2:4);
[m,n]=size(c);
D=repmat(eye(n),m,1);
D(logical(D))=c(:)
1 Comment
Distelfink
on 4 Mar 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(:)
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),[])'
1 Comment
Distelfink
on 4 Mar 2022
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!