필터 지우기
필터 지우기

Finding if numbers are within range

조회 수: 213 (최근 30일)
GOENG
GOENG 2015년 4월 24일
답변: Wupadrasta Santosh Kumar 2020년 10월 1일
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.

답변 (4개)

Andrei Bobrov
Andrei Bobrov 2015년 4월 24일
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 2015년 4월 24일
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 2015년 4월 24일
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 2020년 10월 1일
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) = [];

카테고리

Help CenterFile Exchange에서 Line Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by