Logical operator not evaluating correctly

조회 수: 1 (최근 30일)
Andrew
Andrew 2023년 1월 26일
답변: Star Strider 2023년 1월 26일
Given the provided array X, create an array Y that is:
equal to 0 if the corresponding element of X is between -5 and +5, inclusive
equal to -1 if the corresponding element of X is less than -5
equalt to +1 if the corresponding element of X is greater than 5
Here is what I have:
Y = (~(X >= -5 & X <= 5) | (-1*(X < -5)) | (X>5)).
Why is the X < -5 not evaluationg to -1?

채택된 답변

Star Strider
Star Strider 2023년 1월 26일
Only two comparisons are actually required here —
X = linspace(-7, 7, 15);
Y = -(X < -5) + (X > 5);
Check_Result = [X; Y]
Check_Result = 2×15
-7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 -1 -1 0 0 0 0 0 0 0 0 0 0 0 1 1
.

추가 답변 (2개)

Walter Roberson
Walter Roberson 2023년 1월 26일
A|B is an or test and returns a logical value -1 is nonzero which is considered true, and since you or everything together you are going to end up with logical true for those entries.
Try adding the results of the computation

Les Beckham
Les Beckham 2023년 1월 26일
I would do this in separate steps.
X = randi([-20, 20], [1 15])
X = 1×15
3 -6 2 6 -7 -8 -7 13 17 -3 5 -13 -17 5 -1
Y = zeros(size(X));
Y(X < -5) = -1;
Y(X > 5) = 1
Y = 1×15
0 -1 0 1 -1 -1 -1 1 1 0 0 -1 -1 0 0

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by