How to check if a generated number is between 2 values
101 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (3)
Benjamin Thompson
am 7 Okt. 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 =
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 Kommentare
Image Analyst
am 7 Okt. 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
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 Kommentare
Steven Lord
am 7 Okt. 2022
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 Kommentare
Siehe auch
Kategorien
Mehr zu Timing and presenting 2D and 3D stimuli finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!