Finding if numbers are within range
271 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(4 个)
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;
0 个评论
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
0 个评论
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)
0 个评论
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) = [];
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!