Can someone explain this loop?

1 回表示 (過去 30 日間)
Tri Dang
Tri Dang 2021 年 6 月 14 日
回答済み: Walter Roberson 2021 年 6 月 14 日
A = [0 1.7 2; 3 4 8; 4.2 3 8];
numEven = 0;
for k = 1:numel(A)
if mod(A(k),2) == 0
numEven = numEven+1;
end
end
Why numEven =5 ? Can someone explain? As I understand mod(A(k),2 == 0 is logical command therefore the sum of mod(A(k),2 supposed to be equal 5, and 5+1=6?
  2 件のコメント
SALAH ALRABEEI
SALAH ALRABEEI 2021 年 6 月 14 日
it counts the even numbers by checking the reminder of dividing by 2.
What is ur A!!
Tri Dang
Tri Dang 2021 年 6 月 14 日
Oh I editted the question
Can you check?
Thanks

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

採用された回答

Walter Roberson
Walter Roberson 2021 年 6 月 14 日
The count starts out 0. Then you start going through the array in linear index order. Each time you find an even number, you increase the count by 1.
The first 0 is even so you increase the count from 0 to 1
The 2 is even so you increase the count from 1 to 2
The 4 and 8 are even so you increase the count to 3 and then 4
The 8 is even so you increase the count from 4 to 5.
There is nothing in the code that would add 1 to the 5.
Another way of writing the code is
numEven = nnz(mod(A,2) == 0)
with no loops.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by