You could use the randi
function to determine the locations of where to insert the ones, and then place those ones into your matrix. For example for n
ones:
matrix = zeros(256,256);
onesIndices = randi([0 256*256],1,n);
matrix(onesIndices) = 1;
One problem with this approach is that randi
can generate repeat values, though for this example, where the size of the matrix is large and the number of ones is low, this is pretty unlikely. You could test if this is the case and "reroll:" so if sum(sum(matrix))
is less than n
you know you had a repeat value.
Edit: a better approach is to use randperm
instead of randi
and only take the first n
elements. This should prevent there from being repeats and having to re-roll.