# How do I code for this random situation?

조회 수: 3(최근 30일)
NAA 2023년 3월 20일
댓글: Image Analyst 2023년 3월 20일
On a r*c size grid, 55% of the sites are randomly filled with X, 2% randomly filled with Y, and the rest are empty
##### 댓글 수: 3표시 이전 댓글 수: 2숨기기 이전 댓글 수: 2
Image Analyst 2023년 3월 20일
@NAA, OK try it this way:
r = 10;
c = 20;
output = nan(r, c);
numX = round(0.55 * r * c) % Number of elements to place an X into.
numY = round(0.02 * r * c) % Number of elements to place a Y into.
X = 1;
Y = 2;
output(1 : numX) = X;
output(numX + 1 : numX + numY) = Y;
randomIndexes = randperm(numel(output));
output = reshape(output(randomIndexes), [r, c])
There are other ways that would work also.

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

### 채택된 답변

Image Analyst 2023년 3월 20일
Obviously we can't give you the full solution because you're not allowed to turn in our code as your own.
Hint:
output = nan(r, c);
numX = round(0.55 * r * c); % Number of elements to place an X into.
numY = round(0.02 * r * c); % Number of elements to place a Y into.
Two ways to do it:
1. You can do it vectorized using randperm (assign the X to the first numX elements, then assign Y to the next numY elements, then use randperm to scramble the order), or
2. you can do it brute force using a for loop to place the x value and another loop to place the Y value, but only in the location if the value is a nan (not an X).
##### 댓글 수: 1표시 없음숨기기 없음
NAA 2023년 3월 20일
it's not the hw problem, this is just part of an assumption I am making to get started, but thank you!

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

### 범주

Find more on Logical in Help Center and File Exchange

R2022b

### Community Treasure Hunt

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

Start Hunting!

Translated by