2

How can I create in Matlab a matrix (20 X 12) with random distribution of numbers 1 and 0, when in each column I must have 40% of numbers 1 and 60% of numbers 0? this must be random distribution.

Anyone could help me?

Thanks a ton!

3 Answers 3

4

An efficient method is:

  1. Generate matrix of uniform random values between 0 and 1.
  2. For each column compute the 40-percentile.
  3. For each column, set to 1 the entries that are lower or equal than the computed percentile, and set to 0 the remaining entries. This assures the desired fraction of values per column.

This can be done easily with prctile and bsxfun:

rows = 20;
cols = 12;
p = 40; %// percent of 1 values

A = rand(rows,cols); %// uniform random values between 0 and 1
perc = prctile(A,p); %// percentile of each column
A = bsxfun(@le, A, perc); %// 1 if lower or equal than percentile, 0 otherwise
Sign up to request clarification or add additional context in comments.

1 Comment

perfect..this function is new for me..i will check out in help. thanks
1

Here is a robust method, set the first 40% of each column to be 1 and then just randomly reorder each column.

m=20;
n=12;
M = zeros(m,n);
M(1:round(m*0.4),:) = 1;

for col = 1:n
    M(:,col) = M(randperm(m), col);
end

1 Comment

thanks Dan. i was also using the same approach but was not getting correct output .finally found my mistake from ur reply.
0

This could be one "aggressive" approach -

N = 10000;%%// A big number to choose 12 columns from
A = round(rand(20,N));
out = A(:,find(sum(A,1)==round(0.4*size(A,1)),12))

Let us know if this works for you!

4 Comments

thanks. it worked but what is the purpose of having large value of N? i didnt understand its use !!
Basically we are creating a large matrix (20xN) and from that choosing the first 12 columns that satisfy the criteria of 40% ones. Pretty easy to understand and use, if you ask me :)
yes i got..you are actually selecting 12 columns satisfying given condition.having limited N say 30 wouldn't make it sure that required number of entries will be obtained..
Exactly, that's why "aggressive".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.