Add elements in matrix without sum-function

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

 採用された回答

Guillaume
Guillaume 2018 年 12 月 3 日

0 投票

"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 件のコメント

Linh Tran
Linh Tran 2018 年 12 月 6 日
Thank you for your answer, Guillaume!
I solved it by doing a for-loop in a for-loop for the rows resp. the columns. :)
Guillaume
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)
Linh Tran
Linh Tran 2018 年 12 月 7 日
Ahh! Of course!
I will keep this in mind for further tasks. Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2018 年 12 月 3 日

コメント済み:

2018 年 12 月 7 日

Community Treasure Hunt

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

Start Hunting!

Translated by