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

131 次查看(过去 30 天)
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 个评论

请先登录,再进行评论。

采纳的回答

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

更多回答(12 个)

Buwaneka Dissanayake
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 个评论
DGM
DGM 2022-7-25
编辑:DGM 2022-7-25
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 2020-9-19
%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 2023-2-10
编辑:DGM 2023-2-10
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 个评论
Rik
Rik 2023-2-10
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 2023-2-10
编辑:DGM 2023-2-10
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 2015-5-28
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]

Srishti Saha
Srishti Saha 2018-4-7
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
Ajith Bharadwaj 2020-2-3
function summa = halfsum(A)
[row col] = size(A);
for ii = 1:row
for jj = ii:col
summa = summa + A(ii,jj);
end
end
  7 个评论
DGM
DGM 2023-2-10
@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
DGM 2024-2-7
编辑:DGM 2024-2-7
@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
function summa=halfsum(A)
t=triu(A);
list=sum(t);
s=0;
for n=list
s=s+n;
end
summa=s;
end
  6 个评论
Rik
Rik 2023-2-9
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 2023-2-9
编辑:DGM 2023-2-9
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
saurav Tiwari 2020-6-25
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

youssef boudhaouia
youssef boudhaouia 2020-7-27
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 个评论
youssef boudhaouia
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

请先登录,再进行评论。


Vishnu V
Vishnu V 2022-10-14
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
ZUEN BOZA 2023-9-2
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 个评论
DGM
DGM 2023-9-2
编辑:DGM 2023-9-2
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
Aramis 2024-2-6
THE BEST ANSWER , Simple&Fast
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 个评论
DGM
DGM 2024-2-7
编辑:DGM 2024-2-7
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Parallel Computing Fundamentals 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by