Finding odd and even values without functions
古いコメントを表示
Is it possible to identify if a value is even or odd using for loops instead of using a function (Ex. mod)? If possible, can someone show me?
2 件のコメント
James Tursa
2020 年 4 月 2 日
What have you done so far? What specific problems are you having with your code?
Jose Grimaldo
2020 年 4 月 2 日
採用された回答
その他の回答 (2 件)
per isakson
2020 年 4 月 2 日
Try this
>> a=1:12
a =
1 2 3 4 5 6 7 8 9 10 11 12
>> (-1).^[a]==1
ans =
1×12 logical array
0 1 0 1 0 1 0 1 0 1 0 1
>> (-1).^[-a]==1
ans =
1×12 logical array
0 1 0 1 0 1 0 1 0 1 0 1
>> (-1).^[1e9+a]==1
ans =
1×12 logical array
0 1 0 1 0 1 0 1 0 1 0 1
>>
4 件のコメント
darova
2020 年 4 月 2 日
what about float numbers
per isakson
2020 年 4 月 3 日
even and odd implies whole numbers. Whole numbers are by default implemented as flint, floating point integers. I don't think that "floating point precision error" will be a problem here.
darova
2020 年 4 月 3 日
Agree. It was just late. Don't know why i asked it
per isakson
2020 年 4 月 5 日
Better safe than sorry; one should be sceptical to the combination of double and ==.
John D'Errico
2020 年 4 月 5 日
編集済み: John D'Errico
2020 年 4 月 5 日
A = 1:10;
A == fix(A/2)*2
ans =
1×10 logical array
0 1 0 1 0 1 0 1 0 1
As long as A is composed of integers, this will suffice as a test for even-ness. Yes, I know that is not a word. How about parity instead? ;-) For non-integers of course the concept of even and odd is meaningless.
However, when the target is itself an integer class, then you can be slightly more concise, as the fix is no longer needed. The divide by 2 automatically truncates the fractional part implicitly, casting the division into an integer.
A = uint8(1:10);
A == A/2*2
ans =
1×10 logical array
0 1 0 1 0 1 0 1 0 1
カテゴリ
ヘルプ センター および File Exchange で Resizing and Reshaping Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!