# 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

234 views (last 30 days)
Deepanshu Parihar on 28 May 2015
Commented: DGM on 10 Feb 2023
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
Moses Patson on 26 Nov 2022
This code may fail the row and column vector test.

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

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
##### 2 CommentsShow 1 older commentHide 1 older comment
DGM on 25 Jul 2022
Edited: DGM on 25 Jul 2022
Of all the inefficient loop-based approaches on this page, this appears to be the most wasteful by far. For every single element of the array, you calculate the sum of the entire array and then discard the result. The only sum that doesn't get discarded is the last one. As a consequence, the time required grows rapidly as the matrix size increases -- all for nothing.
Try feeding this a large array. For a 400x400 matrix, this takes roughly 1000x as much time as the other loop-based examples, and nearly 6000x as much time as @Sean de Wolski's concise and efficient answer. Would you dare to feed it a 4000x4000 matrix?

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

DGM on 10 Feb 2023
Edited: DGM on 10 Feb 2023
Okay, it's my turn. Let's try something absolutely ridiculous.
% some test arrays
A = magic(1000); % square
B = [A A]; % wide
C = [A; A]; % tall
% Sean de Wolski's example as a reference
f = @(x)sum(sum(triu(x))); % a sensible choice
ref = [f(A) f(B) f(C)];
testme = [halfsum_poly(A) halfsum_poly(B) halfsum_poly(C)];
% check the results
isgood = isequal(testme,ref)
isgood = logical
1
% literally just draw a triangle over the values you want
function summa = halfsum_poly(A)
sz = size(A);
mxsz = max(sz);
x = [0 1 1 0]*mxsz; % use max() to support non-square inputs
y = [0 0 1 0]*mxsz + 0.5; % offset to capture main diagonal
summa = sum(A(mk)); % apply the mask
end
Wait, as ridiculous as that is, it actually works? Of course it works. These are basic image processing tools. It doesn't use triu(), and it even works for non-square inputs. I don't think anyone would expect this silliness to be fast, but it doesn't have the worst complexity out of the examples on this page. For large inputs (1000x1000), it's comparable in speed to many of the examples here.
Would your TA accept this if you turned it in for your homework? Wanna gamble?
Are there more sensible ways to solve the problem using logical indexing? Yes.
Are there ways which might seem wasteful, but might have advantages? Yes.
Are there ways to do it with loops that are both concise and fast? Yes.
What's the lesson here? If you're going to post an answer among many others, try to post something that adds to the information present. Test it to make sure it works (you can run it right here in the editor). Describe what your code does (comments and otherwise). Does your answer provide particular benefits? Does it have relative drawbacks?
##### 2 CommentsShow 1 older commentHide 1 older comment
DGM on 10 Feb 2023
Edited: DGM on 10 Feb 2023
I think the cautionary warning was more to imply that copying a curiously-uncommon answer is a good way to invite scrutiny, especially if your other efforts in the class are comparably lazy.
After I posted that, I was tempted to change it to calculate the sum of the lower triangular matrix instead, just to keep everyone honest (and attentive).
I kind of wanted to post all the silly examples I tested to emphasize that there's plenty of opportunity to try something different, but I figured that would be too much free stuff. I don't know. Maybe if I flip those it'd be fair.
Yeah, I avoid length() so much that I'd have never thought of that.

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.

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
##### 2 CommentsShow 1 older commentHide 1 older comment
Image Analyst on 8 Oct 2022
@Muhammad Amir Javed you could use a double for loop. The starting value for the inner for loop would be the current value of the outer for loop.

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
DGM on 10 Feb 2023
@Amit Jain Both this example and Muhammad's have the same problems as @Buwaneka Dissanayake's example. All three of these examples needlessly calculating the entire array sum on every iteration, discarding every result but the last one. This is massively wasteful, and the cost grows rapidly as the array size increases.
I commented that Dissanayake's code was much slower than the reference example. To put that in perspective, for a 4000x4000 input, your example will take approximately 2.2 hours to calculate the sum, something that most good examples can easily do in less than 200ms.

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
DGM on 9 Feb 2023
Edited: DGM on 9 Feb 2023
I hate to continue, but this is one of the threads I try to keep ... well I wouldn't call it "tidy", but you get the idea. I think there's a side to these interactions that's being overlooked.
@Bengisu: At least as far as my own similar remarks are concerned, asking "why did you post this" in cluttered threads like these is often in part a response to the ubiquity of answers which are:
• not notably unique from existing answers
• not explained or commented (or formatted)
• not correct in their results
• incomplete or result in errors
• verbatim copies of other answers on the same page
• not answers at all or are irrelevant to the question
How many of the answers on this thread describe their conceptual approach to the solution? How many explain what makes their approach better or different than other similar answers? Would a novice reader know if there is relative benefit in yet another uncommented loop-based example? Are there any? Disregarding ethics, it's poor communication, and lots of it.
From my own perspective, we're not merely trying to help people with MATLAB; sometimes we also try to help people write good questions and answers. Some of us are just trying to keep things organized. Maybe some of us are trying to help people improve in ways that are more important than this week's MATLAB homework. In that effort, some of us have the patience of a saint, but the rest of us are mere humans.
Considering that students do get in trouble for offloading their work on the forum, I think calling this sort of thing cheating is a fair generalization, despite the arguable existence of exceptions. That said, I think the ship has already sailed with regards to providing answers to this simple assignment. I personally wouldn't mind if someone else posted a different answer and had something to say about it, though others are free to disagree.

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 CommentsShow 1 older commentHide 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;

Vishnu V on 14 Oct 2022
function summa = halfsum(A)
[row,col]=size(A);
summa=0;
for r=1:row
for c=1:col
if r==c
for x = r
for y = c:col
summa=summa+A(x,y);
end
end
end
end
end