Add elements in matrix without sum-function
조회 수: 15 (최근 30일)
이전 댓글 표시
Hello,
How can I sum all the elements in an undefined matrix(the built-in homeworktester puts in its A) without using the sum-function?
This is what I've gotten so far. The result I get is the same element in the matrix multiplied with the numel(A).
function summa = summa_element(A)
[m,n]=size(A)
a=A(m,n)
summa=0;
for i=1:numel(A)
summa= summa + a
end
end
댓글 수: 0
채택된 답변
Guillaume
2018년 12월 3일
"The result I get is the same element in the matrix multiplied with the numel(A)."
Well, yes, you never change a inside the loop. So, you're just adding a, numel(A) times. I'm sure you can figure out what you need to do with a inside the loop.
댓글 수: 3
Guillaume
2018년 12월 6일
Glad, you solved it. A simpler option would have been to replace
summa = summa + a
by
summa = summa + A(i)
and keep everything else the same (or optionally delete the [m,n]=... and a=... since they're no longer needed)
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!