Take the 2-minute tour ×

I am trying to generate a random sequence of 0s and 1s such that any time a sequence is generated, the probability of 1 is 0.3. I tried the following in Matlab

%%clear all; %%close all;clc; %%(rand(1,10)<=0.3)

The problem is that every time I run this, I get a different proportion of 1s. Can anyone suggest a better approach?

share|improve this question
What have You tried? –  angainor Oct 21 '12 at 21:00
I tried using the randi function but everytime i get diff no. of ones in the sequence –  happyme Oct 21 '12 at 21:16
You should probably show the code and explain the problem with it better to get some guidance here. –  angainor Oct 21 '12 at 21:24
%%clear all; %%close all;clc; %%(rand(1,10)<=0.3) –  happyme Oct 21 '12 at 21:27
@Mathias, ahhh, that makes sense. However, in this case, if the 1's and 0's are presented as a sequence then the sequence is not truly random, because the final element of the sequence can be known based on the preceding elements. –  cjh Oct 21 '12 at 23:33
show 6 more comments

1 Answer

up vote 6 down vote accepted

If you want to have exactely a propotion of 0.3 at the end, you can do:

n=1000; %should be a multiple of 10.
x=[ones(1,n*3/10) zeros(1,n*7/10)];

Basically, it creates an array with a 0.3 proportion of 1.

Then, it permutes it randomly.

share|improve this answer
Not familiar enough with Matlab, but assuming randperm is a shuffle, this approach is correct: create a sequence containing 30% of 1s and 70% of 0s, and shuffle it. –  Mathias Oct 21 '12 at 23:13
In this case you get the precise proportion to be 0.3, but the final element of the sequence will always be a deterministic function of the preceding elements. More generally, if the data are presented sequentially, then the probability of the n-th element being "1" is a function of the values of the n-1 preceding elements. –  cjh Oct 21 '12 at 23:37
@cjh, Yes, You're totally right. I think that what the OP really want is what he wrote in the question: x=(rand(1,n)<=0.3). However, he was complaining about the fact that he gets 0.3012 in the end, so I thought that the randperm solution could help him to get precisely 0.3 –  Oli Oct 21 '12 at 23:41
Worth noting that this obviously isn't guaranteed to have that proportion at any point in the list, only at the end---I can't determine from the question which is required –  Ben Allison Oct 22 '12 at 12:50
Thanks guys! I could have the solution through rand perm and OLI is right with using the rand function!!! –  happyme Oct 24 '12 at 20:59
add comment

Your Answer


