Find values in a column that fall between two numbers
14 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Rivers Cuomo
el 31 de Ag. de 2022
Respondida: dpb
el 31 de Ag. de 2022
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), :)
0 comentarios
Respuesta aceptada
dpb
el 31 de Ag. de 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.
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Testing Frameworks en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!