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!

채택된 답변

Massimo Zanetti
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

추가 답변 (1개)

KSSV
KSSV 2016년 10월 6일
A = [ 8 1 6
3 5 7
4 9 2];
C = 15 ;
C = C*eye(size(A)) ;
iwant = A+C
  댓글 수: 2
Gobert
Gobert 2016년 10월 6일
Thanks,Siva, but it does not produce the following:
D =
23 9 6
15 20 15
4 21 17
That's a shortcut to produce the following (I had done).
D =
23 1 6
3 20 7
4 9 17

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

카테고리

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