MATLAB: How to get sum of numbers appearing in triangle in a matrix

I want to find sum of numbers appearing in right triangular part from bottom right corner to top left corner in a 2-D matrix like
o = [1 2 3 4;5 6 7 8]
f = [1,2,3,4; 5,6,7,8; 2,3,4,5]
sum of o = 1+5+6+7+8 = 27
sum of f = 1+5+6+2+3+4+5 = 26

Best Answer

You need to decide if the row and column are in the lower triangle and if it is, sum it up. This code works for both your (badly-named) "o" and your "f".
o = [1 2 3 4;5 6 7 8]
f = [1,2,3,4; 5,6,7,8; 2,3,4,5]
m = f % or set equal to f.
[rows, columns] = size(m)
deltaX = columns - 1;
deltaY = rows - 1;
slope = deltaY / deltaX
theSum = 0;
for row = 1 : rows
for col = 1 : columns
x = col;
y = row;
yOnSlope = slope*(x-1)+1;
fprintf('row (y) = %d, col (x) = %d, yOnSlope = %.2f', y, x, yOnSlope);
if y >= yOnSlope
% It's in the lower triangle
theSum = theSum + m(row, col);
fprintf('<-- This is in the lower triangle');
end
fprintf('\n');
end
end
% Echo to command window.
theSum
In the command window:
row (y) = 1, col (x) = 1, yOnSlope = 1.00<-- This is in the lower triangle
row (y) = 1, col (x) = 2, yOnSlope = 1.33
row (y) = 1, col (x) = 3, yOnSlope = 1.67
row (y) = 1, col (x) = 4, yOnSlope = 2.00
row (y) = 2, col (x) = 1, yOnSlope = 1.00<-- This is in the lower triangle
row (y) = 2, col (x) = 2, yOnSlope = 1.33<-- This is in the lower triangle
row (y) = 2, col (x) = 3, yOnSlope = 1.67<-- This is in the lower triangle
row (y) = 2, col (x) = 4, yOnSlope = 2.00<-- This is in the lower triangle
theSum =
27
and for "f":
row (y) = 1, col (x) = 1, yOnSlope = 1.00<-- This is in the lower triangle
row (y) = 1, col (x) = 2, yOnSlope = 1.67
row (y) = 1, col (x) = 3, yOnSlope = 2.33
row (y) = 1, col (x) = 4, yOnSlope = 3.00
row (y) = 2, col (x) = 1, yOnSlope = 1.00<-- This is in the lower triangle
row (y) = 2, col (x) = 2, yOnSlope = 1.67<-- This is in the lower triangle
row (y) = 2, col (x) = 3, yOnSlope = 2.33
row (y) = 2, col (x) = 4, yOnSlope = 3.00
row (y) = 3, col (x) = 1, yOnSlope = 1.00<-- This is in the lower triangle
row (y) = 3, col (x) = 2, yOnSlope = 1.67<-- This is in the lower triangle
row (y) = 3, col (x) = 3, yOnSlope = 2.33<-- This is in the lower triangle
row (y) = 3, col (x) = 4, yOnSlope = 3.00<-- This is in the lower triangle
theSum =
26