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

15 次查看(过去 30 天)
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 个评论
Muhammad Usman Saleem
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 2015-5-27
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.

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2015-5-27
编辑:Stephen23 2015-5-27
>> 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

更多回答(3 个)

Anna Rozanska
Anna Rozanska 2017-3-24
The answer should be 9 not 7 , though.
  1 个评论
Stephen23
Stephen23 2017-3-24
编辑:Stephen23 2017-3-24
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.

请先登录,再进行评论。


Sumit Kumar Sharma
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
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');

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by