Zero elements in a matrix more higher than ones (MATLAB)
1 view (last 30 days)
Show older comments
Dear members,
I want to generate a random binary matrix like this:
M=216;
N=432;
H=randi([0,1],M,N);
But I want to add a condition such that the number of ones '1' must not exceed 3 in each column.
It means for each column we can find (one, two or three ones).
How can I do that please !
0 Comments
Accepted Answer
Mike Croucher
on 5 Nov 2021
This is almost certainly not the most efficient way of doing it but it seems to work. Will need the statistics and ML toolbox for the randsample function.
numRows = 216;
numCols = 432;
H = zeros(numRows,numCols);
% How many ones are we going to have per column? Between one and three
numOnesPerCol = randi([1,3],[1,numCols]);
% Randomly choose where on each colum these ones are going to be
for col=1:numCols
numOnes = numOnesPerCol(col); % Number of ones in this column
indices = randsample(numRows,numOnes) % Which rows are the ones going to be put
H(indices,col) = 1; % Put the ones in this column
end
More Answers (0)
See Also
Categories
Find more on Logical 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!