Find values in a column that fall between two numbers

10 ビュー (過去 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 Center および File ExchangeTesting Frameworks についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by