Matrix elements where row index higher than column index

I have a m by n matrix, say 10 by 10. I want to sum all the values where the row index is higher than the column index. So I want M(2:10,1), M(3:10,1:2), M(4:10,1:3), and so on, without having to type all this out.

 Réponse acceptée

Guillaume
Guillaume le 25 Oct 2018
Modifié(e) : Guillaume le 25 Oct 2018
sum(sum(tril(M, -1)))
is one way to do it.

3 commentaires

madhan ravi
madhan ravi le 25 Oct 2018
Modifié(e) : madhan ravi le 25 Oct 2018
+1 cool!
If you're using release R2018b or later, you can simplify that code slightly.
sum(tril(M, -1), 'all')
One of the main use cases for that syntax is when you don't know how many dimensions the array that you're trying to sum has (and so don't know how many times you'd need to nest sum calls -- are you trying to sum a matrix with sum(sum(...)) or a 3-D array with sum(sum(sum(...)))?) but it works fine for this case too.
Ooh! I completely missed that in the release notes. Although why is it filed under Data Analysis rather than Mathematics or Language and Programming?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Produits

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by