Find values in a column that fall between two numbers

조회 수: 14 (최근 30일)
Rivers Cuomo
Rivers Cuomo 2022년 8월 31일
답변: dpb 2022년 8월 31일
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