How to find the sum of all column vectors of the elements on the kth diagonal of a square matrix in Matlab ?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hello, sir/madam. I need your help to find a solution to the following case.
n = 3;
A = magic(n)
B = diag(diag(A,0));
C = sum(sum(B))
D = triu(A) + tril(A) + diag(B(B>0)+C) - (2*diag(diag(A,0)))
A =
8 1 6
3 5 7
4 9 2
C =
15
D =
23 1 6
3 20 7
4 9 17
As can be seen, I found the main diagonal elements and added their sum to each column vector element, as shown in D. But, I can’t do that for following column vector elements (for any n value):
B1 =
0 1 0
0 0 7
0 0 0
B1 = sum(sum(B1)) = 8
B2 =
0 0 6
0 0 0
0 0 0
B2 = sum(sum(B2)) = 6
B3 =
0 0 0
3 0 0
0 9 0
B3 = sum(sum(B3)) = 12
B4 =
0 0 0
0 0 0
4 0 0
B4 = sum(sum(B4)) = 4
Can anyone help me to write a code that can do that so that I can obtain the following output ?
D =
23 9 6
15 20 15
4 21 17
Thank you!
댓글 수: 0
채택된 답변
Massimo Zanetti
2016년 10월 6일
편집: Massimo Zanetti
2016년 10월 6일
Here it is the code that does the work. Inspect the function diag and partial results at each iteration.
n = size(A,1);
for k = -n+1:n-1
%get kth diagonal sum
v = sum(diag(A,k));
%add the sum to the kth diagonal of a
A = A + diag(v*ones(n-abs(k),1),k)
end
댓글 수: 2
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!