How do you use logical operators for this problem in multiple unnested if statements?

조회 수: 1 (최근 30일)
I'm given the following:
x=0:3:21;
y=10;
z=15;
When x < y and z, the code has to dispaly "Value is less that y and z". When y<x<z, the code has to display "Value is between y and z". When x > y and z, the code has to display " Value is greater than y and z." I was able to do this with a for loop and nested if statements, but I also have to write the code using unnested if statements. My code either gives logical array instead of a displayed answer or an error statement. This is what I have so far, and it gives a logical array.
x=0:3:21;
y=10;
z=15;
if x<y %& x<z %y is less than z, so if x is less than y, then x must also be less than z
disp('Value is less than y and z')
elseif x>z & x>y %z is greater than y, so if x is greater than z, then x must also be greater than y
disp('Value is more than y and z')
else y<x<z
disp('Value is between y and z')
end
ans = 1×8 logical array
1 1 1 1 1 1 1 1
Value is between y and z

답변 (1개)

Image Analyst
Image Analyst 2022년 2월 26일
Replace
else y<x<z
with
elseif (y < x) && (x < z)
  댓글 수: 1
Steven Lord
Steven Lord 2022년 2월 27일
Because x is a vector that won't work. You could wrap the conditions in all or any to get it to work or you could use the non-short-circuiting and operator &.
x = 1:10;
y = 0;
z = 11;
all(y < x) && all(x < z) % true
ans = logical
1
(y < x) & (x < z) % vector of true values
ans = 1×10 logical array
1 1 1 1 1 1 1 1 1 1
(y < x) && (x < z) % error
Operands to the logical and (&&) and or (||) operators must be convertible to logical scalar values.

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

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by