Generating random ones and zeros controllably

23 ビュー (過去 30 日間)
Sam Lee
Sam Lee 2016 年 3 月 23 日
編集済み: dpb 2016 年 3 月 23 日
I am making a simple game in MATLAB that requires ones and zeros to be generated in a 5x5 matrix. I want to prespecify the number of ones and let the program generate them randomly among the zeros in the matrix. I tried using the rand function but I couldn't find a way to do the above.
How can I generate the required matrix?

採用された回答

Ced
Ced 2016 年 3 月 23 日
編集済み: Ced 2016 年 3 月 23 日
You can generate a vector ( or matrix if you like ) with the desired number of zeros and ones, and then permute them randomly using randperm.
Example for a 5x5 matrix:
N = 25; % total number of elements
N_ones = 10; % number of ones
v = zeros(N,1);
v(1:N_ones,1) = 1; % vector with desired entries
% Now, scramble the vector randomly and reshape to desired matrix
A = reshape(v(randperm(N)),5,5);

その他の回答 (2 件)

dpb
dpb 2016 年 3 月 23 日
編集済み: dpb 2016 年 3 月 23 日
doc randperm % note the second optional input...
Will leave as "exercise for the student" the actual application but is straightforward... :)
ADDENDUM
See some verbose ways so I'll throw in another...shorter is simply
N=5; % array size (dimension)
nOnes=10; % number of ones
a=zeros(N); % allocate the array
a(randperm(numel(a),nOnes))=1; % set the one locations

Charles Dunn
Charles Dunn 2016 年 3 月 23 日
Interesting question. There are probably a couple ways to do this. I would check out the randperm function.
sz = [5 5];
N = prod(sz);
n = 5;
vals = cat(2,ones(1,n),zeros(1,N - n));
result = reshape(vals(randperm(N)),sz);

カテゴリ

Help Center および File ExchangeRandom Number Generation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by