How to express this if statement?

If I have a array X = [x1 x2 x3 x4 x5] and another array Y = [y1 y2 y3 y4 y5], every element in those arrays is read from another program and values will be different for each time, and x1 and y1 are corresponded x and y conponents for the object 1. If I want to have a if statement to ckeck whether there exists any element in X is between a certain range and the corresponding element in Y is also bewteen another range, how should I do that? Also, if we have the relation r = sqrt(x^2+y^2), how should I write when the above condition is satisitied and then the corresponded x and y values will have the corresponding r value?
x = [x1 x2 x3 x4 x5];
y = [y1 y2 y3 y4 y5];
r = sqrt(x.^2+y.^2);
if % for example if I want any element in x is between the range -55<x<0 and there exists a corresponded y element is between 0 to 80
%when above if statement is satisfied, we calculate the value r for the set of x and y value that satisfied above conditions
end

답변 (1개)

Walter Roberson
Walter Roberson 2020년 12월 8일

0 개 추천

mask = -55 < x & x < 0 & 0 < y & y < 80;
selected_x = x(mask);
selected_y = y(mask);
selected_r = sqrt(selected_x.^2 + selected_y.^2);

댓글 수: 2

Rui Luo
Rui Luo 2020년 12월 8일
Hi, could you simply explain the code and how should I add these codes into above structure?
the code replaces your
if % for example if I want any element in x is between the range -55<x<0 and there exists a corresponded y element is between 0 to 80
%when above if statement is satisfied, we calculate the value r for the set of x and y value that satisfied above conditions
end
selected_r is the r value for the set of x and y that satisfied the condition.
x is a vector. -55<x is a vector of logical values. x<0 is a vector. & of two vectors proceeds pairwise and returns logical true only if both corresponding entries were non-zero... that is, only if both conditions are true.
End result of the & together is a vector of logical values.
When you index a vector with logical values, then the elements corresponding to false are not selected, and the elements corresponding to true are selected. (If there are fewer logical indices than array elements, the remainder are not selected.)

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

카테고리

도움말 센터File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

제품

릴리스

R2020a

질문:

2020년 12월 7일

댓글:

2020년 12월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by