How to check if a generated number is between 2 values

26 views (last 30 days)
I am trying to program multiple steps for a percentage value.
I am using rand() to generate a random number and I want to use the output to define a range.
Var = rand();
if Var >= 0.9
elseif Var < 0.9 and >= 0.8
elseif Var < 0.8 and >= 0.7
I am tring to get 90th percentile, 80th percentile, 70th percentile.

Answers (3)

Benjamin Thompson
Benjamin Thompson on 7 Oct 2022
You can use the logical operator & to combine multiple tests. You can either get an index vector with the results of all tests as I am showing here, or you can check single values one by one and use this test in an if statement.
» rand(2,1)
ans =
» var = rand(2,1)
var =
» I = (var > 0.1) & (var < 0.5)
I =
2x1 logical array

Image Analyst
Image Analyst on 7 Oct 2022
Not sure what you're asking. Of course for a known distribution, like rand() which does the uniform distribution, you can do as you have done (except use "&&" instead of "and" and you'd need to use Var twice) to determine if a single variable is in a certain percentile range, because the percentile ranges are known in advance for that distribution.
Actually if you know the ranges, you can just drop down from the max to 0 and not bother checking the lower limit, though it's perhaps more readable and understandable if you do
Var = rand();
if Var >= 0.9
elseif Var >= 0.8
elseif Var >= 0.7
%etc. for other numbers
If you don't know the distribution, you can use histogram or histcounts to find the actual percentiles of your data.

Steven Lord
Steven Lord on 7 Oct 2022
Other options that may be able to do what you want include discretize and interp1.
x = rand(5, 1)
x = 5×1
0.6115 0.7907 0.6304 0.2460 0.1239
p = 0:10:100;
y1 = discretize(x, p/100, p(2:end)) % or
y1 = 5×1
70 80 70 30 20
y2 = interp1(p/100, p, x, 'next')
y2 = 5×1
70 80 70 30 20




Community Treasure Hunt

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

Start Hunting!

Translated by