calculate the number of odd fence values instead of printing them

12 ビュー (過去 30 日間)
Shuoze Xu
Shuoze Xu 2022 年 3 月 28 日
コメント済み: Shuoze Xu 2022 年 3 月 28 日
Sample Output:
Given A = [ 5, 4, 6, 7, 3 ; 1, 2, 3, 4, 5 ; 5, 6, 4, 2, 4 ; 4, 5, 3, 2, 1]
% output demo
There are 9 odd values in the fence.
% This is my code
% given a matrix
A = [5,4,6,7,3;1,2,3,4,5;5,6,4,2,4;4,5,3,2,1];
% Get the number of rows and columns
[m,n] = size(A);
odd = 0;
for i = 1:m % number of rows
for j = 1:n % number of column
if (mod(A(i),2)~= 0) % if the element is not equal to zero, this is odd values
odd = odd + 1;
end
end
end
fprintf("There are %d odd values in the fence",odd);
There are 9 odd values
but in my code, it is shows There are 15 odd values in the fence.
How to improve this code?
  1 件のコメント
Image Analyst
Image Analyst 2022 年 3 月 28 日
What is your definition of fence? Do you mean matrix?

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

採用された回答

Voss
Voss 2022 年 3 月 28 日
if (mod(A(i,j),2)~= 0)
Use A(i,j) instead of A(i)
  4 件のコメント
Image Analyst
Image Analyst 2022 年 3 月 28 日
And why do you say there are 9 values? My code below shows there are 10 values. Why do we disagree? Which one did I count that you say should not be counted?
Shuoze Xu
Shuoze Xu 2022 年 3 月 28 日
There are 9 odd values showed on the pdf, I think it may a mistake

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2022 年 3 月 28 日
A = [ 5, 4, 6, 7, 3 ; 1, 2, 3, 4, 5 ; 5, 6, 4, 2, 4 ; 4, 5, 3, 2, 1]
A = 4×5
5 4 6 7 3 1 2 3 4 5 5 6 4 2 4 4 5 3 2 1
numOddNumbers = nnz(rem(A, 2))
numOddNumbers = 10

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by