Clear Filters
Clear Filters

Info

This question is locked. Reopen it to edit or answer.

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

93 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
  4 Comments

Accepted Answer

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

More Answers (7)

Buwaneka Dissanayake
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 Comments
DGM
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
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

DGM
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)];
% logical addressing using a polygonal mask
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
mk = poly2mask(x,y,sz(1),sz(2)); % generate logical mask
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 Comments
Rik
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
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
Joseph Cheng on 28 May 2015
your input should be
input = [1 2 3;4 5 6;7 8 9]
and not
input = [1 2 3 4 5 6 7 8 9]
  1 Comment
Joseph Cheng
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
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

ERTIZA HOSSAIN SHOPNIL
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
  6 Comments
Rik
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
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.

youssef boudhaouia
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
  4 Comments
youssef boudhaouia
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

This question is locked.

Community Treasure Hunt

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

Start Hunting!