How to find the sum of all column vectors of the elements on the kth diagonal of a square matrix in Matlab ?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Gobert
el 6 de Oct. de 2016
Comentada: Massimo Zanetti
el 6 de Oct. de 2016
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 comentarios
Respuesta aceptada
Massimo Zanetti
el 6 de Oct. de 2016
Editada: Massimo Zanetti
el 6 de Oct. de 2016
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 comentarios
Más respuestas (1)
KSSV
el 6 de Oct. de 2016
A = [ 8 1 6
3 5 7
4 9 2];
C = 15 ;
C = C*eye(size(A)) ;
iwant = A+C
2 comentarios
Ver también
Categorías
Más información sobre Operating on Diagonal Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!