Sum of all the elements after the matrix diagonal

10 views (last 30 days)
Hello. I am trying to calculate the total sum of all the elements in any given matrix, including row array and column array, starting from the cell where the row index is equal to column index (matrix diagonal). I am picking up an extra value in my code, and I don't know why. Here is my code:
(function syntax with a matrix given)
(getting the number of the elements in the matrix using the "size" function)
(initializing my output count "answer")
for r = 1:row
for c = 1:col
if col >= row
answer = col + answer;
end
end
end
So for a matrix A [1 2 3; 4 5 6; 7 8 9], the answer should be 26 and I am getting 27 and I can't figure why. I've tried to use the "sum" function but it gets just way to complicated and I get lost with referencing of the columns/rows. Also I must use the "for loop" and no super fancy build-in functions.
  2 Comments
Matt J
Matt J on 9 Mar 2020
Edited: Matt J on 9 Mar 2020
Also I must use the "for loop" and no super fancy build-in functions.
It is absurd to call this "super fancy",
>> sum( triu(A), 'all')
ans =
26
Dmitriy
Dmitriy on 9 Mar 2020
Thanks Matt, but:
"Assessment result: incorrect [1 2 3; 4 5 6; 7 8 9]
The submission must not contain the following functions or keywords: triu"
That's why said "no super fancy build-in functions". I wish I could use them but the solution must be based on "for... loop" function only.

Sign in to comment.

Accepted Answer

Matt J
Matt J on 9 Mar 2020
Edited: Matt J on 9 Mar 2020
answer=0;
for r = 1:row
for c = 1:col
if c >= r
answer = A(r,c) + answer;
end
end
end
answer =
26
  5 Comments
Matt J
Matt J on 9 Mar 2020
Yes, an unfortunately misleading test case.
Dmitriy
Dmitriy on 9 Mar 2020
Edited: Dmitriy on 9 Mar 2020
That's the code I wrote in the first 15 minutes of thinking about the problem, but I was getting the wrong answers with it, so I abondoned the idea completly.
P.S. I ran your code and found out that I had previously the iverted logic and that's why mine didn't work. Thanks, man! Problem solved.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!