Title: Not getting the correct expectation in MATLAB
Tags: matlab;statistics;probability
Question: I am trying to make the random number generator work, however my expectation is not correct (unless I am fundamentally misunderstanding something).
I have this preset array :
array=[1 0 0]
I proceed to generate a random index between 1 and 3 using the rand() function in MATLAB.
index=round(1+2*rand(1,1),0); %generate random index between 1 and 3
Subsequently, I am trying to put together an array of entries accessed by the randomly generated index for some number of iterations:
answer_array=[] %answer holder
for i = 1:1:iterations %Loop for the set number of iterations
index=round(1+2*rand(1,1),0);
answer_array=[answer_array array(index)]
Then I try to sum the number of 1's in the answer_array and find the ratio of that to the number of iterations
temp=0;
for i=1:size(answer_array,2)
temp=temp+answer_array(1,i) %just sum all array contents as they're either 1 or 0
ratio=temp/iterations
No matter how large I set my iterations, the ratio angelahartman@example.net.
Should it not be 0.33? My reasoning is that if I randomly pick the index myself, I have 1/3 chance of getting 1. Thus if I continue picking for a large number of times, my success chance will converge at 1/3?
Comment: Your results are skewed because the range of random values that will result in an index of `1` is `[1.0, 1.5)`. The range of values that will result in an index of `2` is `[1.5, 2.5)`, or a probability of `0.50`. If you check index `3`, you should also see a probability of `0.33`.

Comment: This worked. Thanks! Do you know why the standard rand wasn't working?

Comment: Try this expected value is 0.33 : `iterations =1000;a=[1 0 0];r = randi(3,1,iterations);sum(a(r))/iterations

Comment: Instead of `round` I think you should use `floor(rand*3)+1` or `ceil(rand*3)`



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:03/01/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<matlab><statistics><probability>', 'Title': 'Not getting the correct expectation in MATLAB', 'ViewCount': 52, 'id': 42541475, 'user_AboutMe': None, 'user_AccountId': 10178799.0, 'user_DisplayName': 'Drakhlur', 'user_Reputation': 27.0, 'user_Views': 5.0, 'user_id': 7516443.0}}