How to make a matrix from trace of the original matrix ?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Yamada Taro
am 5 Sep. 2022
Kommentiert: Yamada Taro
am 6 Sep. 2022
When I have a square matrix A like the one in the picture, I want to create a matrix B which is the sum of the kth diagonal component to the right below itself, is there any easy way to write this?
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1116955/image.png)
Currently, I am calculating in the form of creating reduced matrices and getting the jth diagonal component of each reduced matrix, but I feel it is quite slow and inefficient.
A = reshape(1:9,3,3);
B = zeros(3,3);
for i = 1:3
A_partial = A(i:end,i:end);
for j = 1:3-i+1
B(i,i+j-1) = sum(diag(A_partial,j-1));
B(i+j-1,i) = sum(diag(A_partial,-1*(j-1)));
end
end
A
B
0 Kommentare
Akzeptierte Antwort
Dyuman Joshi
am 5 Sep. 2022
Bearbeitet: Dyuman Joshi
am 5 Sep. 2022
Building on your approach - Breaking the matrix into smaller matrices and assigning the diagonal sums to the corressponding elements.
y=spiral(3)
mat=y;
for i=1:size(y,1)-1
for j=1:size(y,2)-1
mat(i,j)=sum(diag(y(i:end,j:end)));
end
end
mat
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Operating on Diagonal Matrices 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!