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

1 回表示 (過去 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 Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by