Sum of all the elements after the matrix diagonal

5 visualizaciones (últimos 30 días)
Dmitriy
Dmitriy el 9 de Mzo. de 2020
Editada: Dmitriy el 9 de Mzo. de 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 comentarios
Matt J
Matt J el 9 de Mzo. de 2020
Editada: Matt J el 9 de Mzo. de 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 el 9 de Mzo. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Matt J
Matt J el 9 de Mzo. de 2020
Editada: Matt J el 9 de Mzo. de 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 comentarios
Matt J
Matt J el 9 de Mzo. de 2020
Yes, an unfortunately misleading test case.
Dmitriy
Dmitriy el 9 de Mzo. de 2020
Editada: Dmitriy el 9 de Mzo. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by