# 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

117 visualizaciones (últimos 30 días)
Deepanshu Parihar el 28 de Mayo de 2015
Comentada: Voss el 7 de Feb. de 2024
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
##### 15 comentariosMostrar 13 comentarios más antiguosOcultar 13 comentarios más antiguos
Nadeem U Rehman el 10 de Dic. de 2020
thank you @Rik
Moses Patson el 26 de Nov. de 2022
This code may fail the row and column vector test.

Iniciar sesión para comentar.

Sean de Wolski el 28 de Mayo de 2015
f = @(x)sum(sum(triu(x))) % make function
f(magic(3)) % use it
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

### Más respuestas (12)

Buwaneka Dissanayake el 21 de Jun. de 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 comentariosMostrar NingunoOcultar Ninguno
Arshdeep Singh el 9 de Ag. de 2020
can you explain the logic of this function
DGM el 25 de Jul. de 2022
Editada: DGM el 25 de Jul. de 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?

Iniciar sesión para comentar.

Pragyan Dash el 19 de Sept. de 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
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
THIERNO AMADOU MOUCTAR BALDE el 19 de Dic. de 2020
very clean thanks

Iniciar sesión para comentar.

DGM el 10 de Feb. de 2023
Editada: DGM el 10 de Feb. de 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 comentariosMostrar NingunoOcultar Ninguno
Rik el 10 de Feb. de 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 el 10 de Feb. de 2023
Editada: DGM el 10 de Feb. de 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.

Iniciar sesión para comentar.

Joseph Cheng el 28 de Mayo de 2015
input = [1 2 3;4 5 6;7 8 9]
and not
input = [1 2 3 4 5 6 7 8 9]
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Joseph Cheng el 28 de Mayo de 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.

Iniciar sesión para comentar.

Srishti Saha el 7 de Abr. de 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 comentariosMostrar NingunoOcultar Ninguno
Muhammad Amir Javed el 8 de Oct. de 2022
How to sum upper triangle of matrix without using triu?
Image Analyst el 8 de Oct. de 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.

Iniciar sesión para comentar.

Ajith Bharadwaj el 3 de Feb. de 2020
function summa = halfsum(A)
[row col] = size(A);
for ii = 1:row
for jj = ii:col
summa = summa + A(ii,jj);
end
end
##### 7 comentariosMostrar 5 comentarios más antiguosOcultar 5 comentarios más antiguos
DGM el 10 de Feb. de 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 el 7 de Feb. de 2024
Editada: DGM el 7 de Feb. de 2024
@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

Iniciar sesión para comentar.

ERTIZA HOSSAIN SHOPNIL el 21 de Mayo de 2020
function summa=halfsum(A)
t=triu(A);
list=sum(t);
s=0;
for n=list
s=s+n;
end
summa=s;
end
##### 6 comentariosMostrar 4 comentarios más antiguosOcultar 4 comentarios más antiguos
Rik el 9 de Feb. de 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 el 9 de Feb. de 2023
Editada: DGM el 9 de Feb. de 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.

Iniciar sesión para comentar.

saurav Tiwari el 25 de Jun. de 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 comentariosMostrar NingunoOcultar Ninguno
saurav Tiwari el 25 de Jun. de 2020
cool
awesome coding
Walter Roberson el 25 de Jun. de 2020
Incorrect code. This calculates sums of an entire row, not the sum of the diagonal and right of the diagonal.

Iniciar sesión para comentar.

youssef boudhaouia el 27 de Jul. de 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 comentariosMostrar 2 comentarios más antiguosOcultar 2 comentarios más antiguos
youssef boudhaouia el 3 de Ag. de 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 el 4 de Ag. de 2020
You do not need the if condition if you use
for j=i:s(2)

Iniciar sesión para comentar.

Vishnu V el 14 de Oct. de 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
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

ZUEN BOZA el 2 de Sept. de 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
##### 1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
DGM el 2 de Sept. de 2023
Editada: DGM el 2 de Sept. de 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.

Iniciar sesión para comentar.

Aramis el 6 de Feb. de 2024
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
##### 4 comentariosMostrar 2 comentarios más antiguosOcultar 2 comentarios más antiguos
DGM el 7 de Feb. de 2024
Editada: DGM el 7 de Feb. de 2024
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 el 7 de Feb. de 2024
Bring on the purge.

Iniciar sesión para comentar.

### Categorías

Más información sobre Parallel Computing Fundamentals en Help Center y File Exchange.

### Community Treasure Hunt

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

Start Hunting!

Translated by