How to check if a generated number is between 2 values
100 次查看(过去 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.
0 个评论
回答(3 个)
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
0 个评论
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.
0 个评论
Steven Lord
2022-10-7
Other options that may be able to do what you want include discretize and interp1.
x = rand(5, 1)
p = 0:10:100;
y1 = discretize(x, p/100, p(2:end)) % or
y2 = interp1(p/100, p, x, 'next')
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Image display and manipulation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!