function with input a matrix and calcualte sum of elements of its diagonal and right of it

11 views (last 30 days)
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
  2 Comments
Muhammad Usman Saleem
Muhammad Usman Saleem on 27 May 2015
Testing answer is 5 , instead of 7 . Kindly check where is need of correction in my code. Thanks in advance for assistance
Nobel Mondal
Nobel Mondal on 27 May 2015
The bug in your code is in the condition check line. It should be -
if i==j || i<j
However, using in-built functions triu and sum would definitely be the way to go, as Stephen replied.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 27 May 2015
Edited: Stephen23 on 27 May 2015
>> 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

More Answers (3)

Anna Rozanska
Anna Rozanska on 24 Mar 2017
The answer should be 9 not 7 , though.
  1 Comment
Stephen23
Stephen23 on 24 Mar 2017
Edited: Stephen23 on 24 Mar 2017
Muhammad Usman Saleem, who asked this question, wrote that they wanted the output to be 7: "Testing answer is 5 , instead of 7". Not only that, they also accepted an answer that gives 7 as the output. Note also that the sum of the upper triangle+diagonal of the example matrix is 4+2+1=7 (this sum is what Muhammad Usman Saleem requested).
Please explain why you think that sum should be equal to 9.

Sign in to comment.


Sumit Kumar Sharma
Sumit Kumar Sharma on 4 Jun 2020
function summa=halfsum(x)
[m,n]=size(x);
sum=0
for p=1:m
for q=1:n
if p<=q
sum=sum + x(p,q);
end
end
end
summa=sum;
end

Prasanth Venkatesan
Prasanth Venkatesan on 23 Aug 2020
function summa =halfsum(m)
[row,col]=size(m);
for r=1:row;
for c=r:col;
a(r,c)=m(r,c);
b=a;
end
end
summa= sum(b,'all');

Products

Community Treasure Hunt

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

Start Hunting!