How to express this if statement?
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (1)
Walter Roberson
el 8 de Dic. de 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 comentarios
Walter Roberson
el 8 de Dic. de 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.)
Ver también
Categorías
Más información sobre Operators and Elementary Operations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!