How can I choose an element from a vector according to its probability ?

4 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Steven Lord
Steven Lord am 24 Mai 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
prob = 0.9989
select = Ang_1(find(rand<cumsum(prob),1)) % select angle according to "prob"
select = 10
%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)]
probabilities = 1×6
0 0.0541 0.1622 0.3243 0.5676 1.0000
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)
results = 10×3 table
x values categories _______ ______ ___________________ 0.66418 80 [0.56757, 1] 0.33411 45 [0.32432, 0.56757) 0.22314 30 [0.16216, 0.32432) 0.76124 80 [0.56757, 1] 0.33686 45 [0.32432, 0.56757) 0.90657 80 [0.56757, 1] 0.13988 20 [0.054054, 0.16216) 0.49154 45 [0.32432, 0.56757) 0.51494 45 [0.32432, 0.56757) 0.83691 80 [0.56757, 1]
  2 Kommentare
omar th
omar th am 24 Mai 2023
@Steven Lord First Thanks for your response. Actually that prop is scalar due to measured via the mentioned equation BUT its changing in each iteration of for loop. Now I want choose ONLY one of these options according to prob in each iteration of for loop ?? Thanks for your
for j=1:100
for i=1:1
% here the prob is changable in each iteration
end
end
Steven Lord
Steven Lord am 25 Mai 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Produkte


Version

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by