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

조회 수: 2 (최근 30일)
high speed
high speed 2021년 11월 5일
댓글: high speed 2021년 11월 5일
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 !

채택된 답변

Mike Croucher
Mike Croucher 2021년 11월 5일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by