Sum of all the elements after the matrix diagonal

5 Ansichten (letzte 30 Tage)
Dmitriy
Dmitriy am 9 Mär. 2020
Bearbeitet: Dmitriy am 9 Mär. 2020
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 Kommentare
Matt J
Matt J am 9 Mär. 2020
Bearbeitet: Matt J am 9 Mär. 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 am 9 Mär. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Matt J
Matt J am 9 Mär. 2020
Bearbeitet: Matt J am 9 Mär. 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 Kommentare
Matt J
Matt J am 9 Mär. 2020
Yes, an unfortunately misleading test case.
Dmitriy
Dmitriy am 9 Mär. 2020
Bearbeitet: Dmitriy am 9 Mär. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by