Zero elements in a matrix more higher than ones (MATLAB)

1 Ansicht (letzte 30 Tage)
high speed
high speed am 5 Nov. 2021
Kommentiert: high speed am 5 Nov. 2021
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 !

Akzeptierte Antwort

Mike Croucher
Mike Croucher am 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

Weitere Antworten (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by