MATLAB Answers

0

how can i generate the random numbers for specific probabilites

Asked by waqas muhammad on 19 Oct 2019
Latest activity Commented on by waqas muhammad on 21 Oct 2019
Hello everyone.
I need to choose a random number for each probablitiy. The code is in the attachment. The code is perfect, i just need a random number for each probability.
Its really confusing for me. So if somebody can help me to solve ths problem, i will be very thankfull..
Thanks

  3 Comments

It's not clear what you're asking for. Also, there is no attached code.
This is the code. if you look at the code. I have pt in the code and R denotes th random number [0,1]. if i take the probability of pt, it will give me some values, now for each value i need one random number .... if you see in the photo. this is just an example.. there are some values for probabilty (column 2) and the are also some values for random numbers column (4). basically the random number are from 0-100 in this photo. now for 0.01 probability it will give me a random number of 0, for probability 0.15,it will give me a random number bewtween 1-15, for 0.20 probability it will give me a random number between 16-35 as written in the table. in this way for each probability value i will get one random number..
Now in my code the range of random number is [0,1]...
I still don't know what you want. Your code does not make that easier. Do you want to generate random numbers between two integers? That's very easy.
N = 100; % generate N random numbers
rnge = [1 15]; % on this interval
nums = randi(rnge,1,N); % generate random integers
nums2 = rand(1,N)*14 + 1; % generate random (non-integer) numbers in rnge

Sign in to comment.

1 Answer

Answer by Bruno Luong
on 19 Oct 2019
Edited by Bruno Luong
on 19 Oct 2019
 Accepted Answer

v = [ 0, 15, 25, 35, 45, 20]; % values
P = [0.01, 0.15, 0.20, 0.50, 0.12, 0.02]; % the correspond probability
c = cumsum([0 P]);
c = c / c(end); % make sure the cumulative sum terminates exactly with 1
n = 100; % length of the random sequence
[~,i] = histc(rand(1,n),c);
r = v(i)

  1 Comment

bundle of thanks Sir.
Your comment really helped me alot. i got idea from your comment and it was worked perfect.
Once again Thanks alot

Sign in to comment.