MATLAB: Function with input a matrix and calcualte sum of elements of its diagonal and right of it

for loopif statementMATLABmatlab functionmatrix

Hi every one, I want to make a function that take two dimensional matrix as input and return sum of its diagonal (index for row and col will be same) and element right to this diagonal(sum of upper triangular elements). I am using that code & to me this is looking fine
function mysum=halfsum(A)
[row col]=size(A);
mysum=0;
for i=1:row
for j=1:col
if i==j && i<=j
mysum=mysum+A(i,j);
end
end
end
end
When i test for
>> a
a =
1 2
3 4
>> halfsum(a)
ans =
5

Best Answer

>> a = [1,2;3,4]
a =
1 2
3 4
Method one:
>> sum(sum(triu(a)))
ans =
7
Method two:
>> sum(a(triu(true(size(a)))))
ans =
7
@Muhammad Usman Saleem: you are very busy using MATLAB, now would be a good time to learn to avoid using nested loops for solving everything (as if it was a low-level language), and start to understand the speed and power of vectorized code: faster, neater and less buggy!
If you are doing one of those courses where they insist that the students write everything using loops and basic arithmetic, then try this (note that there is no if statement):
function out = halfsum(A)
[row,col] = size(A);
out = 0;
for rr = 1:row
for cc = rr:col
out = out + A(rr,cc);
end
end
end
and then we can test it to confirm the output (note that it only works with matrices!):
>> halfsum(a)
ans =
7
Related Question