# 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

135 views (last 30 days)
Deepanshu Parihar on 28 May 2015
Commented: Voss on 7 Feb 2024 at 20:15
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
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
Arshdeep Singh on 9 Aug 2020
can you explain the logic of this function
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?
Rik on 10 Feb 2023
I'm tempted to create a new account so I can give you two upvotes. (and as a TA I would personally accept this answer)
You missed the golden opportunity to use the length function.
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
Muhammad Amir Javed on 8 Oct 2022
How to sum upper triangle of matrix without using triu?
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.
DGM on 7 Feb 2024 at 19:40
Edited: DGM on 7 Feb 2024 at 19:42
@Ajith Bharadwaj Why are you posting code that does not work?
halfsum(magic(3))
Unrecognized function or variable 'summa'.

Error in solution>halfsum (line 7)
summa = summa + A(ii,jj);
function summa = halfsum(A)
[row col] = size(A);
for ii = 1:row
for jj = ii:col
summa = summa + A(ii,jj); % summa is never allocated
end
end
end

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 9 Feb 2023
There is a fine line (or overlap) between rudeness and clarity/unabiguity. I will have followed up those questions with something along the lines of 'these are not rhetorical questions' (or at least I should have).
My questions to you were actually serious, and not at all intended as bullying. If you see a legitimate purpose to this thread, I would welcome the explanation. If I'm missing something, I honestly would like to know.
Same goes for my wording. If you have a suggestion for me that has the same level of transparency but conveys the message a bit (or a lot) nicer, please feel free to suggest it. For this kind of interaction I use canned responses, so a suggestion now will improve many posts to come.
I hope you do reply if you have any constructive/actionable feedback. I hope my record speaks for itself and that you can help me improve it further.
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
saurav Tiwari on 25 Jun 2020
cool
awesome coding
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
youssef boudhaouia on 3 Aug 2020
First we initialize the output summa. Second we assign s as the size of the matrix M . In fact , size(M) returns a vector with two values. The first value s(1) is the row number and the second value s(2) is the column number. The variable i is for the row indexes( from 1 to s(1)) and the variable j is for column indexes(from 1 to s(2)) . In every time where we find a value of the matrix which has a column index ( j ) higher or equal to the row index ( i ), we add this value to summa, and so over, until we find the total sum. If the condition (j>=i) is not true, the variable summa stays the same and doesn't change, that means : summa=summa .
I hope it's clear now . you can ask if there's something u r not convinced with
Walter Roberson on 4 Aug 2020
You do not need the if condition if you use
for j=i:s(2)

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

ZUEN BOZA on 2 Sep 2023
function summa=halfsum(A)
[row col] = size(A);
summa=0;
for r = 1:row
for c = 1:col
if r>c
A(r,c)=0;
end
summa=summa+A(r,c);
end
end
DGM on 2 Sep 2023
Edited: DGM on 2 Sep 2023
This is at least the twelfth samey unexplained answer given. You posted another answer, but why? What makes this one different or better? Why should anyone use this version over the others?
It works, but why would you choose to do unnecessary assignment operations
if r>c
A(r,c)=0;
end
summa=summa+A(r,c);
... when you can just omit them?
if r<=c
summa = summa+A(r,c);
end
What's wrong with that? I imagine the problem with removing this needless complication is simply that it would mean that your answer is more or less identical to at least three others in this thread.

Aramis on 6 Feb 2024 at 20:36
function summa = halfsum(A)
summa = 0;
sz = size(A);
for row = 1:sz(1)
for col = row:sz(2)
summa = summa + A(row,col);
end
end
end
DGM on 7 Feb 2024 at 19:55
Edited: DGM on 7 Feb 2024 at 20:06
There are at least three examples (including that in the original question) which are not meaningfully different than this example.
The original question restricts inputs to being square, though it's not clear whether that's actually part of the requirements.
These comments are essentially the same, disregarding the use of scalar output from size()
This answer is yet another example of lazy untested copypasta; consequently, it has a minor error
There would have been one more verbatim duplicate of #288818, but I just deleted it.
Duplicate content will end up getting deleted because it doesn't serve any purpose. Changing a variable name or obfuscating a few trivial things isn't a significant difference, even if I might agree that it would be preferable. If you're going to post something on a low-value thread full of samey answers, either post something that demonstrates something significantly different, or be prepared to thoroughly justify why your minor variation is significantly better and should be the one that survives when duplicates get purged.
Voss on 7 Feb 2024 at 20:15
Bring on the purge.