필터 지우기
필터 지우기

How to use for loop and if else condition for multiple conditions

조회 수: 3 (최근 30일)
I am writing a code for Pass/Fail criteria for a application in which if two given conditions are satisfied then it will be pass or it will fail. but I am getting error as,
'Operands to the || and && operators must be convertible to logical scalar values.'
suggest me correction in my code
Thank u in advance!!
for system = 1
if ((A == 45) && (0.8 < B < 1.2))
display('system function - PASS');
else
display('system function - FAIL');
end
end

채택된 답변

John D'Errico
John D'Errico 2020년 3월 25일
편집: John D'Errico 2020년 3월 25일
First, you don'r need a for loop that runs over system, sine you re just assigning it one value! That is, this:
for system = 1
is silly and unecessary. Just write
system = 1;
(removing the now spurious end that went with the for, of course.)
Next, the if is written incorrectly, as MATLAB told you. Just because it is common mathematical shorthand to write this:
(0.8 < B < 1.2)
does not make it work as you wish in MATLAB. Split it into two tests, which is what the shorthand implies anyway.
if ((A == 45) && (0.8 < B) && (B < 1.2))
Finally, what was the immediate reason why your code failed in the first place?
'Operands to the || and && operators must be convertible to logical scalar values.'
That tells you either A or B, or both of them, were not scalar variables. You cannot have an if statement that loops over a vector or array. That is, an if statement is not an implied loop.
I would also STRONGLY recommend that you read the getting started tutorials. If you have made 3 basic mistakes in your first 3 lines of code, this tells me you never bothered to read any documentation. READ THE MANUAL. It was put there to get you started.
  댓글 수: 1
Ashwini  More
Ashwini More 2020년 3월 25일
Thank you for your help and suggestion!!
but I want to clarify that this code is not for one set of values, actually it is for large data in which 'system' value can be '0' or '1' and hence I am using for loop
here A & B are not scalar variables as both have number of values i.e. it is vector. and I want to apply to code for this range that for certain period, system= 1, and for that range, these both conditions should be satisfy or it will fail system function.
So, how can I update my code to get the result for vector or array.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by