MATLAB: How to create a random binary matrix with equal number of ones in each column

equal numbermatrix

Hi All,
I want to create a random binary matrix with equal number of ones in each column.
Appreciate if anyone have an idea to implement this in Matlab.
Thanks.

Best Answer

This is how I did it:
% Set up parameters.
rows = 10;
columns = 15;
onesPerColumn = 4;
% Initialize matrix.
m = zeros(rows, columns, 'int32')
for col = 1 : columns
% Get random order of rows.
randRows = randperm(rows);
% Pick out "onesPerColumn" rows that will be set to 1.
rowsWithOne = randRows(1:onesPerColumn);
% Set those rows only to 1 for this column.
m(rowsWithOne, col) = 1;
end
% Display m
m