Finding odd and even values without functions

조회 수: 2 (최근 30일)
Jose Grimaldo
Jose Grimaldo 2020년 4월 1일
편집: John D'Errico 2020년 4월 5일
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
James Tursa 2020년 4월 2일
What have you done so far? What specific problems are you having with your code?
Jose Grimaldo
Jose Grimaldo 2020년 4월 2일
Im trying to separate evenly the array into two variables. The odd index and the even index using for loops. Cant figure it out.
A= % 8x1 array
[r,c]=size(A)
BA=A(1)
CA=A(2)
for i=1:r-1
BA(i+1)=A(i+2)
BC(i+1)=B(i+1)
end

댓글을 달려면 로그인하십시오.

채택된 답변

darova
darova 2020년 4월 2일
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

추가 답변 (2개)

per isakson
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
darova 2020년 4월 3일
Agree. It was just late. Don't know why i asked it
per isakson
per isakson 2020년 4월 5일
Better safe than sorry; one should be sceptical to the combination of double and ==.

댓글을 달려면 로그인하십시오.


John D'Errico
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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by