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

조회 수: 3(최근 30일)
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 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
##### 댓글 수: 1표시숨기기 없음
Bilese 2022년 11월 17일
Thank you!

댓글을 달려면 로그인하십시오.

### 범주

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