How to check if a generated number is between 2 values
조회 수: 102 (최근 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
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!