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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by