Problem evaluating OR operator
    조회 수: 7 (최근 30일)
  
       이전 댓글 표시
    
I have what should be a simple problem, but after being stuck for a while, I dont know how to solve it.
Answer = '1';
if Answer == ('1') || ('2')
    fprintf("inside if")
end
That works as it should, but when evaluating this case, it gives out an error which I don't understand why.
Answer = 'aa';
if Answer == ('1') || ('2')
    fprintf("inside if")
else
    fprintf("if didnt work")
end
I've checked out ANY and ALL functions, but dont seem to work for this. Im pretty sure this is a basic question but I'm stuck.
Thanks
댓글 수: 0
채택된 답변
  Jan
      
      
 2022년 11월 8일
        
      편집: Jan
      
      
 2022년 11월 8일
  
      if Answer == ('1') || ('2')
Matlab evaluates this condition accourding to the precedence order of the operators from left to right:
1. Answer == ('1')
This replies true or false. In the next step this is used as 1st input of the || operator:
2. true || ('2')    % or
   false || ('2')
 Both is not, what you want, but the (almost!) correct syntax is:
if Answer == ('1') || Answer == ('2')
Now the comparisons are processed at first - see: https://www.mathworks.com/help/matlab/matlab_prog/operator-precedence.html 
The next problem is that == is an elementwise operator:
'aa' == '1'    
replies [false, false] , one logical for each element of the [1 x 2] char vector on the left. In the oiginal comparison this is used as 1st input of ||, which accepts scalar inputs only.
Use strcmp to compare char vectors instead:
if strcmp(Answer, '1') || strcmp(Answer, '2')
With strings (in double quotes), the == comparison is working:
Answer = "1";
if Answer == "1" || Answer == "2"
    fprintf("inside if")
end
This is similar to another frequently ask question:
if a < b < c    
This does not check, if b is between a and c. Correct:
is a < b && b < c
댓글 수: 2
  Steven Lord
    
      
 2022년 11월 8일
				Other approaches that you could use instead of strcmp include matches, ismember, or (if you have a number of fixed sets of potential values that you want to match) switch and case.
s = ["1", "2", "3"]
matches(s, '2')
ismember(["2", "4"], s)
x = '2';
switch x
    case {'1', '2'}
        disp('Entered either 1 or 2')
    case {'3'}
        disp('Entered 3')
    otherwise
        disp('Entered something other than 1, 2, or 3')
end
추가 답변 (0개)
참고 항목
카테고리
				Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


