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

2 vues (au cours des 30 derniers jours)
high speed
high speed le 5 Nov 2021
Commenté : high speed le 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 !

Réponse acceptée

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

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by