Finding if numbers are within range

417 visualizaciones (últimos 30 días)
GOENG
GOENG el 24 de Abr. de 2015
Respondida: Wupadrasta Santosh Kumar el 1 de Oct. de 2020
Hello, just trying to figure out a way to find a number in a vector within range. I'm trying practice for loops but still bad at it.
%the range is from 1 to 10
xRange = [5 2 1 -1 5 67 3]
for inside = xRange(1,1):length(xRange)
if xInside, out of range
delete number
else
store number in new vector/keep it in the same vector
end
I tried doing something like
if xInside == 0 xInside(xInside==0) = []; %which sould delete the 0
end
but what if 0 was part of it?
so i tried it in nan
if xInside < max(xRange) | xInside > min(xRange)
turn the number into NaN. end
but not sure how to get that last part.

Respuestas (4)

Andrei Bobrov
Andrei Bobrov el 24 de Abr. de 2015
r = [1, 10];
xRange = [5 2 1 -1 5 67 3];
ii = xRange >= r(1) & xRange <= r(2)
out = xRange;
out(~ii) = nan;

Ingrid
Ingrid el 24 de Abr. de 2015
I do not think you need to use a for loop for this problem, instead using a vectorized solution is much faster and easier to read
belowRange = (xRange < 1);
aboveRange = (xRange > 10);
iRemove = or(belowRange,aboveRange);
xRange(iRemove) = [];
should do the trick

Rushikesh Tade
Rushikesh Tade el 24 de Abr. de 2015
input_vector=1:100;
range_upper_limit=50;
range_lower_limit=25;
indices_in_input_vector_within_the_range= intersect(find(input_vector>=range_lower_limit),find(input_vector<=range_upper_limit))
input_vector(
indices_in_input_vector_within_the_range)

Wupadrasta Santosh Kumar
Wupadrasta Santosh Kumar el 1 de Oct. de 2020
My simple take would be:
range = [1 10];
xRange = [5 2 1 -1 5 67 3];
decisionV = (ones(length(xRange),1)*range - (ones(2,1)*xRange)')>0;
OutDecision = ~xor(decisionV(:,1),decisionV(:,2));
xRange(OutDecision) = [];

Categorías

Más información sobre Line Plots 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!

Translated by