If statement not working correctly

조회 수: 16 (최근 30일)
Arnav Barbaad
Arnav Barbaad 2016년 8월 3일
댓글: Steven Lord 2016년 8월 4일
This is driving me insane, I've checked the code 101 times yet can't find any error. This a simple application of if statement.
for i=1:c
parity=mod(x(i),2);
d=bistr(i);
if parity==1 && d==0
display('Hello');
elseif parity==0 && d==0
display('How');
elseif parity==0 && d==1
display('Are');
elseif parity==1 && d==1
display('You');
end
end
i goes from 1 to 192 (c=192). As you can see, parity can either be 0 or 1. d is also either 0 or 1 (it's a matrix of 1s and 0s)
YET THIS CODE WON'T PRINT ANY SINGLE OF THE STRING 'HELLO','HOW','ARE' or 'YOU'. Like I've exhausted all the logical possibilities for parity and d. What is going wrong?
(Yes I've tried printing every single variable at the starting of the loop to see if the loop itself is working fine. IT IS. IT'S JUST THAT THE IF STATEMENT ISN'T GETTING EXECUTED AT ALL!)
  댓글 수: 3
Adam
Adam 2016년 8월 3일
What is 'bistr'?
Presumably whatever it is returning is not actually either a 0 or a 1
Arnav Barbaad
Arnav Barbaad 2016년 8월 3일
You are right Adam, bistr is returning '1' instead of 1

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

채택된 답변

Steven Lord
Steven Lord 2016년 8월 3일
Look at the classes of parity and d. My guess is that parity is a double array but d (being an element of an array I assume is called "bitstr" not "bistr") is a char array.
'1' == 1 % returns false
true == 1 % returns true
1 == 1 % returns true
So if d is a char array, bitstr will look something like:
>> bitstr = char(randi(double('01'), 4, 4))
bitstr =
0111
1010
1111
1100
The elements of bitstr are not equal to 0 or 1 but are equal to either '0' or '1'.
>> bitstr == '1'
  댓글 수: 4
Arnav Barbaad
Arnav Barbaad 2016년 8월 3일
Well got it. The windows belonged to my professor who had a full version license. Since de2bi belongs to communication system toolbox, my student license MATLAB doesn't have it. Hence the error
Steven Lord
Steven Lord 2016년 8월 4일
You could use '1' instead of 1 in your if statement, or subtract '0' from the array (since '0' and '1' are adjacent in ASCII), or convert to logical using:
bistr == '1'

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

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by