Find values in a column that fall between two numbers

14 views (last 30 days)
I have a column vector with ~100,000 values in it ranging from 0 to 20. I need to make a variable that outputs only values between 4 and 40. How do I do this?
For instance, I can find values greater than, but not between:
frqRng=freq(find(freq(:,1) > 4), :)

Accepted Answer

dpb
dpb on 31 Aug 2022
MATLAB requires compound logical tests be written separately...and you don't need find, just the logical result vector..
vLo=4; vHi=40; % use variables, don't bury magic numbers inside code
isIn=(freq(:,1)>vLo)&(freq(:,1)<vHi); % compute the logical index
frqRng=freq(isIn, :); % save the results
This is the type of thing that a helper utility function is very handy to have around -- I use iswithin a bunch to move the compound test out of main code and to return the logical vector that can then be used as functional result. Can make many constructs much more legible to read...
function flg=iswithin(x,lo,hi)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=lo) & (x<=hi);
end
My particular version is inclusive; I've had options for one- or two-sided upper and lower, but have settled that the base function is inclusive as that fits my needs almost always; reserving the other more complex cases to another function.

More Answers (0)

Categories

Find more on Testing Frameworks in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!