필터 지우기
필터 지우기

How to make a matrix from trace of the original matrix ?

조회 수: 3 (최근 30일)
Yamada Taro
Yamada Taro 2022년 9월 5일
댓글: Yamada Taro 2022년 9월 6일
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?
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

채택된 답변

Dyuman Joshi
Dyuman Joshi 2022년 9월 5일
편집: Dyuman Joshi 2022년 9월 5일
Building on your approach - Breaking the matrix into smaller matrices and assigning the diagonal sums to the corressponding elements.
y=spiral(3)
y = 3×3
7 8 9 6 1 2 5 4 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
mat = 3×3
11 10 9 10 4 2 5 4 3
  댓글 수: 1
Yamada Taro
Yamada Taro 2022년 9월 6일
Thank you!
It seems to work well and more sofisticated than my code.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by