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

类别

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