How do I code for this random situation?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
NAA
el 20 de Mzo. de 2023
Comentada: Image Analyst
el 20 de Mzo. de 2023
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 comentarios
Image Analyst
el 20 de Mzo. de 2023
@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.
Respuesta aceptada
Image Analyst
el 20 de Mzo. de 2023
This looks like a homework problem. If you have any questions ask your instructor or read the link below to get started:
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:
- 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
- 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).
Más respuestas (0)
Ver también
Categorías
Más información sobre Annotations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!