# Write a function called halfsum that takes as input an at most two-dimensional matrix A and computes the sum of the elements of A that are in the diagonal or are to the right of it. example, the input is [1 2 3; 4 5 6; 7 8 9],the ans is 26

223 views (last 30 days)
function s = halfsum(A)
[row col] = size(A);
if row ~= col
error('Expecting a square matrix here people...');
end
s = 0;
for ii = 1:row
for jj = ii:col
s = s + A(ii,jj);
end
end
Nadeem U Rehman on 10 Dec 2020
thank you @Rik

Buwaneka Dissanayake on 21 Jun 2020
function summa = halfsum(M)
[a b] = size(M);
if a>1
for n = 1:a;
for m = 1:b;
if n>m;
M(n,m) = 0;
summa = sum(sum(M));
end
end
end
else
summa = sum(M);
end
end
Arshdeep Singh on 9 Aug 2020
can you explain the logic of this function

Joseph Cheng on 28 May 2015
input = [1 2 3;4 5 6;7 8 9]
and not
input = [1 2 3 4 5 6 7 8 9]
Joseph Cheng on 28 May 2015
which if you read carefully the problem statement and the code the input is a 3x3 square matrix. the input you provided it was a 1x9 array.

Sean de Wolski on 28 May 2015
f = @(x)sum(sum(triu(x))) % make function
f(magic(3)) % use it

Pragyan Dash on 19 Sep 2020
%this worked for me. Happy to help!
function summa = halfsum(M)
[row col] = size(M)
summa = 0;
for ii = 1:row;
for jj = 1:col;
if jj >= ii;
summa = summa + M(ii, jj);
end
end
end
very clean thanks

Srishti Saha on 7 Apr 2018
This code works perfectly for me:
%function to compute sum of lower most right side triangle in an X*2 matrix
function u = halfsum(P)
u1 = P(end:-1:1, 1:end);
u2 = triu(u1);
u = sum(u2(:));
end

Ajith Bharadwaj on 3 Feb 2020
function summa = halfsum(A)
[row col] = size(A);
for ii = 1:row
for jj = ii:col
summa = summa + A(ii,jj);
end
end
Amit Jain on 3 Nov 2020
I hope this clears your doubt. You did not tell function what to if there is n ==1 means there is column vector. I have made this correction. Now function works fine. Thanks

ERTIZA HOSSAIN SHOPNIL on 21 May 2020
function summa=halfsum(A)
t=triu(A);
list=sum(t);
s=0;
for n=list
s=s+n;
end
summa=s;
end
Rik on 24 Aug 2020
That means you will have to copy another answer to cheat on your homework. Or think yourself.

saurav Tiwari on 25 Jun 2020
function summa=halfsum(a)
[m,n]=size(a)
for i=1:m
j=1:n
x(i)=sum(a(i,j))
end
summa=sum(x)
end
##### 2 CommentsShowHide 1 older comment
Walter Roberson on 25 Jun 2020
Incorrect code. This calculates sums of an entire row, not the sum of the diagonal and right of the diagonal.

youssef boudhaouia on 27 Jul 2020
A solution with double For-loop:
function summa=halfsum(M)
summa=0;
s=size(M);
for i=1:s(1)
for j=1:s(2)
if j>=i
summa=summa+M(i,j);
else
summa=summa;
end
end
end
Walter Roberson on 4 Aug 2020
You do not need the if condition if you use
for j=i:s(2)

Abdul Quadir Khan on 18 Oct 2020
function summa = halfsum(x)
[row,col] = size(x);
allsum=0;
for n=1:row
for c=n:col
allsum=x(n,c)+allsum;
end
end
summa=allsum;