MATLAB: Random matrix with fix summation

random matrix

Hello
please.
this is my simple code that create (3*3) random matrix that all elements are 0 or 1.
a=randi([0,1],[500,500])
but is there any way that I define the number of elements that are 1. for example number of elements that are 1 be 7000 or in other word summation of matrix "a" be 7000
Thank you.

Best Answer

For older versions of MATLAB without the randperm(n,k) syntax enabled,
n=500^2;
m=7000;
idx=randperm(n);
z=[ones(1,m), zeros(1,n-m)];
a=reshape(z(idx),500,500);