Finding odd and even values without functions
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
James Tursa
le 2 Avr 2020
What have you done so far? What specific problems are you having with your code?
Réponse acceptée
darova
le 2 Avr 2020
What about dividing?
while 1
a = a/2;
if abs(a-1) < 0.01 % if very close to '1'
disp('even')
break;
elseif a < 1 % if smaller than '1'
disp('odd')
break;
end
end
0 commentaires
Plus de réponses (2)
per isakson
le 2 Avr 2020
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 commentaires
per isakson
le 5 Avr 2020
Better safe than sorry; one should be sceptical to the combination of double and ==.
John D'Errico
le 5 Avr 2020
Modifié(e) : John D'Errico
le 5 Avr 2020
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
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!