# How to sum the diagonal numbers and numbers after the diagonal of a matrix

14 visualizaciones (últimos 30 días)
Thomas Sun el 31 de Mzo. de 2020
Respondida: Matt Shellhammer el 31 de Mzo. de 2020
Write a function called halfsum that takes as input a matrix and computes the sum of its elements that are in the diagonal or are to the right of it. The output arguments name is summa.
I have absolutely no idea how to start with this problem. How am I meant to use a for-loop for this?
Thank you very much
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Mohammad Sami el 31 de Mzo. de 2020
Look at function diag and triu

Iniciar sesión para comentar.

### Respuestas (2)

Matt Shellhammer el 31 de Mzo. de 2020
total = 0;
for idx = 1:size(a,1)
total = total + a(idx,idx);
end
or
sum(a(1:(size(a,1)+1):size(a,1)*size(a,2)))
or
sum(diag(a))
and for the indices to the right of it... (assuming its square).
total = 0;
for idx = 1:size(a,2)-1
total = total + a(idx,idx+1);
end
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Bhaskar R el 31 de Mzo. de 2020
function summa = halfsum(inp_mat)
summa = zeros(2,1); % first element is sum of diagonal elements, second is sum of diagonal to right
summa(1) = sum(diag(inp_mat)) %diagnal elemts
summa(2) = sum(diag(inp_mat, 1)) % right to diagonal
end
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

### 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!

Translated by