3

Possible Duplicate:
Generate random number with given probability matlab

I need to create a column vector with random assignments of the number 1, 2 and 3. However i need to be able to control the percentage occurrence of each oif these 3 numbers.

For example, i have a 100 x 1 column vector and I want 30 of the number 1, 50 of the number 2 and 20 of the number 3, in a random assignments.

Community
  • 1
  • 1

2 Answers2

4

I am not sure whether you can do that with rand or randi function.

May be you can write a small module something like this :

bit1 = 1 * ones(1,20);
bit2 = 2 * ones(1,50);
bit3 = 3 * ones(1,30);

bits = [bit1 bit2 bit3];
randbits = bits(:, randperm(length(bits)))
Kiran
  • 8,034
  • 36
  • 110
  • 176
  • Hi, Thanks... what if i need to run this randomisation 30 times. thus how do i create a 30x100 matrix which have 30 different random sequences instead of repeating the random commnand by 30 times. Sorry I am still quite new to MATLAB. – Go Qing Ming Jan 16 '13 at 07:31
  • You have to use a loop in that conditional. Another way is to replace ones(1,20) with ones(30,20) maybe. Then you need to concatenate the array using `horzcat` or `vertcat` – Kiran Jan 16 '13 at 07:54
1

You can do it using the CDF (cumulative destribution function) of the percentage of each number.

pdf = [ 30 50 20 ]/100; % the prob. distribution fun. of the samples
cdf = cumsum( pdf );
% I assume here all entries of the PDF are positive and sum(pdf)==1
% If this is not the case, you may normalize pdf to sum to 1.

The sampling itself

n = 100; % number of samples required
v = rand(n,1); % uniformly samples
tmp = bsxfun( @le, v, cdf );
[~, r] = max( tmp, [], 2 );

As observed by @Dan (see comment below), last line can be replaced with

r = numel(pdf) + 1 - sum( tmp, 2 );

The vector r is a random vector of integers 1,2,3 and should satisfy the desired pdf

Shai
  • 111,146
  • 38
  • 238
  • 371