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

조회 수: 1 (최근 30일)
Bilese
Bilese 2022년 11월 17일
댓글: Bilese 2022년 11월 17일
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

카테고리

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