How to create a matrix with specified numbers in random positions?

I have a problem in Matlab that I don't really know how to approach. I need to create a matrix with specified numbers, but in random positions. So for instance, let's say I want a 20x100 matrix in which 0.2 of all numbers are 1 and 0.8 of all numbers are 0. Thus, the matrix would contain 400 ones and 1600 zeros, but in completely random positions. How to do this? (I'm sorry if this is a trivial question, I'm quite new to Matlab. I would appreciate it if you could recommend some good Matlab learning resources from which I could learn things at the level of my question).

 Accepted Answer

m = desired row size
n = desired column size
f = fraction of 1's to place randomly in result
result = zeros(m,n); % pre-allocate result
k = round(f*m*n); % number of 1's to place in result
result(randperm(m*n,k)) = 1; % randomly put 1's in result using linear indexing
The randperm(m*n,k) call will randomly select k unique integers from the set 1:m*n, and we simply use those unique random integers with linear indexing to fill the associated spots in the result matrix with 1's.
Assumes 0 <= f <= 1.

More Answers (0)

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!