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.

 Accepted Answer

sum(sum(tril(M, -1)))
is one way to do it.

3 Comments

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?

Sign in to comment.

More Answers (0)

Products

Asked:

on 25 Oct 2018

Commented:

on 25 Oct 2018

Community Treasure Hunt

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

Start Hunting!