Sum of all the elements after the matrix diagonal

조회 수: 5 (최근 30일)
Dmitriy
Dmitriy 2020년 3월 9일
편집: Dmitriy 2020년 3월 9일
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
Matt J
Matt J 2020년 3월 9일
편집: Matt J 2020년 3월 9일
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 2020년 3월 9일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2020년 3월 9일
편집: Matt J 2020년 3월 9일
answer=0;
for r = 1:row
for c = 1:col
if c >= r
answer = A(r,c) + answer;
end
end
end
answer =
26
  댓글 수: 5
Matt J
Matt J 2020년 3월 9일
Yes, an unfortunately misleading test case.
Dmitriy
Dmitriy 2020년 3월 9일
편집: Dmitriy 2020년 3월 9일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by