How to make a 31x31 matrix of zeros with 300 1's in random position

조회 수: 3(최근 30일)
x1 = randi([0, 1], [31,31]); %random grid
I have this so far, but I want only 300 1's and not a random amount.

답변(1개)

DGM
DGM 2022년 11월 17일
편집: DGM 2022년 11월 17일
I'm sure this can be cleaned up, but here's one way.
sz = [31 31];
X = zeros(sz); % an array of zeros
X(1:300) = 1; % put 300 ones in there
X = reshape(X(randperm(prod(sz))),sz) % shuffle it
X = 31×31
0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 1 0 1 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 1 1 0 0 0 0 0 0 1 0 0 0 1 1 0 0 1 0 1 0 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 1 0 1 0 0 0 0 1 0 1 0 0 1 1 0 0 0 0 1 0 1 0 1 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 1 1 0 0 1 0 1 0 1 1 0 1 0 0 0 0 1 1 1 1 0 0 0 1 1 1 1 0 1 1 0 0 0 0 0 0 0 0 0 1 0 1 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 1 0 1 1 0 1 0 0 0 1 1 1 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 0 0 1 0 0 0 0 0 0 0 1 0 0 1 0
nnz(X) % check number of nonzero elements
ans = 300

범주

Find more on Creating and Concatenating Matrices 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!

Translated by