How to express this if statement?

4 vues (au cours des 30 derniers jours)
Rui Luo
Rui Luo le 7 Déc 2020
Commenté : Walter Roberson le 8 Déc 2020
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

Réponses (1)

Walter Roberson
Walter Roberson le 8 Déc 2020
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 commentaires
Rui Luo
Rui Luo le 8 Déc 2020
Hi, could you simply explain the code and how should I add these codes into above structure?
Walter Roberson
Walter Roberson le 8 Déc 2020
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.)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Operators and Elementary Operations dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by