Problem with using && operator in if conditional statement with array involved

조회 수: 2 (최근 30일)
i want to use if statement such that if ((x_value==645:650||730:735||815:820||900:905||980:985||1070:1075||1155:1160||1240:1145||1325:1330||1410:1415||1495:1500||1580:1585)&&(y_value==225:230)) out= S(1); end
OR
xx=[645:650,730:735,815:820,900:905,985:990,1070:1075,1155:1160,1240:1245,1325:1330,1410:1415,1495:1500,1580:1585]; yy=[225:230;275:280;325:330;375:380];
if ((x_value==xx)&& y_value==(yy(1,:))) out=S(1) end
but it gives error
Operands to the and && operators must be convertible to logical scalar values.
what is wrong with my code ??

채택된 답변

Steven Lord
Steven Lord 2016년 2월 23일
Use ISMEMBER to check if x_value is an element of your set of desired outcomes.
x = 5;
if ismember(x, [1 3 5 7 9])
disp('First trial, odd number less than 10!');
end
x = 2;
if ismember(x, [1 3 5 7 9])
disp('Second trial, odd number less than 10!');
end

추가 답변 (1개)

MHN
MHN 2016년 2월 23일
편집: MHN 2016년 2월 23일
You should use one "&" if you have logical vectors.
% Correct
a = [1,2];
b = [3,4];
if a==a & b==b
c=1;
end
the following code is wrong:
% Wrong
a = [1,2];
b = [3,4];
if a==a && b==b
c=1;
end
  댓글 수: 3
Asad Ullah
Asad Ullah 2016년 2월 23일
i am using this in a loop and with single & symbol it always skips first if conditions
if any(xx)==x_value & any(yy(1,:))==y_value
out= S(1);
elseif (x_value==648||733||818||903||988||1073||1158||1243||1328||1413||1498||1583)&&(y_value==278)
out= S(2);
elseif (x_value==648||733||818||903||988||1073||1158||1243||1328||1413||1498||1583)&&(y_value==328)
out= S(3);
elseif (x_value==648||733||818||903||988||1073||1158||1243||1328||1413||1498||1583)&&(y_value==378)
out= S(4);
end
MHN
MHN 2016년 2월 23일
편집: MHN 2016년 2월 23일
Because you are using "any" in a wrong way:
any: True if any element of a vector is a nonzero number or is
logical 1 (TRUE)
so the result of any(xx) is always 1 based on your xx vector. And one is not equal to your x_value. What do you want to do in your first statement?

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by