Finding if numbers are within range

276 views (last 30 days)
GOENG
GOENG on 24 Apr 2015
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.

Answers (4)

Andrei Bobrov
Andrei Bobrov on 24 Apr 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 on 24 Apr 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 on 24 Apr 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 on 1 Oct 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) = [];

Community Treasure Hunt

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

Start Hunting!