How can I generate a matrix with exact number of ones(with respect to random distribution) ?

1 view (last 30 days)
I need to generate a random matrix(large one) with the exact number of ones? thanks in advance :)
  2 Comments
Roberto
Roberto on 18 May 2014
Please explain... What's the exact number of ones? and please give an example of the desired result!
mahdi
mahdi on 19 May 2014
I mean for example I need a 5x5 matrix(symmetric) with exact 10 ones but in a random place. (overall number of ones will be 20 because of symmetrically).

Sign in to comment.

Accepted Answer

Matt J
Matt J on 18 May 2014
Edited: Matt J on 18 May 2014
A=zeros(N);
A(randperm(numel(A),nOnes))=1; %nOnes is desired number of ones
  3 Comments
Matt J
Matt J on 19 May 2014
Edited: Matt J on 19 May 2014
Same principle, just randomize over the indices of the upper triangle,
A=zeros(N);
idx=find(triu(ones(size(A)),1));
idx=idx(randperm(numel(idx),nOnes));

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!