Reputation: 83
I'm facing a problem. I have a zeros matrix 600x600
. I need to fill this matrix with 1080 1
s randomly. Any suggestions?
Upvotes: 1
Views: 321
Reputation: 4558
This is one way to do it,
N = 1080; % Number of ones
M = zeros(600); % Create your matrix
a = rand(600^2,1); % generate a vector of randoms with the same length as the matrix
[~,asort] = sort(a); % Sorting will do uniform scrambling since uniform distribution is used
M(asort(1:N)) = 1; % Replace first N numbers with ones.
Upvotes: 2
Reputation: 18187
A = sparse(600,600); %// set up your matrix
N=1080; %// number of desired ones
randindex = randi(600^2,N,1); %// get random locations for the ones
while numel(unique(randindex)) ~= numel(randindex)
randindex = randi(600^2,N,1); %// get new random locations for the ones
end
A(randindex) = 1; %// set the random locations to 1
This utilises randi
to generate 1080
numbers randomly between 1
and 600^2
, i.e. all possible locations in your vectors. The while
loop is there in case it happens that one of the locations occurs twice, thus ending up with less than 1080 1
.
The reason you can use a single index in this case for a matrix is because of linear indexing.
The big performance difference with respect to the other answers is that this initialises a sparse matrix, since 1080/600^2 = 0.3%
is very sparse and will thus be faster. (Thanks to @Dev-iL)
Upvotes: 3
Reputation: 78364
Or, use the intrinsic routine randperm
thusly:
A = zeros(600);
A(randperm(600^2,1080)) = 1;
Upvotes: 6