How to check if a generated number is between 2 values

91 次查看(过去 30 天)
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.
Example:
Var = rand();
if Var >= 0.9
xxx
elseif Var < 0.9 and >= 0.8
yyy
elseif Var < 0.8 and >= 0.7
zzz
end
I am tring to get 90th percentile, 80th percentile, 70th percentile.

回答(3 个)

Benjamin Thompson
Benjamin Thompson 2022-10-7
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 =
0.814723686393179
0.905791937075619
» var = rand(2,1)
var =
0.126986816293506
0.913375856139019
» I = (var > 0.1) & (var < 0.5)
I =
2x1 logical array
1
0

Image Analyst
Image Analyst 2022-10-7
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
xxx
elseif Var >= 0.8
yyy
elseif Var >= 0.7
zzz
%etc. for other numbers
end
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 2022-10-7
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

类别

Help CenterFile Exchange 中查找有关 Timing and presenting 2D and 3D stimuli 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by