Find values in a column that fall between two numbers

14 次查看(过去 30 天)
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), :)

采纳的回答

dpb
dpb 2022-8-31
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Testing Frameworks 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by