How can I choose an element from a vector according to its probability ?
7 views (last 30 days)
Show older comments
I want to select an angle according to the probability. I executed the code below its show me the only FIRST option (only 10 even when I change the probability value its show me the same option). Thank in advance for any help
t=0.1;Ang_1 = [10 20 30 45 80];% this vector of options
for i:1:1
prob = (exp((1/t)*1.2*10^-5))./(exp((1/t)*1.2*10^-4)) % this is probability could be changable each eteration
select = Ang_1(find(rand<cumsum(prob),1)) % select angle according to "prob"
end
0 Comments
Accepted Answer
Steven Lord
on 24 May 2023
t=0.1;Ang_1 = [10 20 30 45 80];% this vector of options
Since your for loop had invalid syntax and you don't use what I suspect you intended to be the loop variable (i) inside the loop I commented it out.
%for i:1:1
prob = (exp((1/t)*1.2*10^-5))./(exp((1/t)*1.2*10^-4)) % this is probability could be changable each eteration
select = Ang_1(find(rand<cumsum(prob),1)) % select angle according to "prob"
%end
Since prob is a scalar, cumsum(prob) is just prob itself. So that find call will return either 1 or [] depending on whether rand generated a number less than prob or not.
If you had a vector of probabilities, like this which uses the value in Ang_1 as the relative frequency of the value:
probabilities = [0 cumsum(Ang_1)./sum(Ang_1)]
then you could use discretize to generate your list.
x = rand(10, 1);
values = discretize(x, probabilities, Ang_1);
Another way to generate these values is as categories.
categories = discretize(x, probabilities, 'categorical');
Let's summarize the results in a table.
results = table(x, values, categories)
2 Comments
Steven Lord
on 25 May 2023
Build your equivalent of the probabilities vector I used in my example in the loop. Once you've done that you can discretize after the loop.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!