How can you randomly pick a position in a matrix and make it count down?

3 visualizaciones (últimos 30 días)
I'm stuck on trying to make a matrix with numbre that are counted down one by one randomly. I'm trying to make a matrix with all 20. Next up I want Matlab to choose a position in this matrix randomly.
Next up I want to make the chosen position in the matrix go down with 1. I also want that when a certain position reached 0, that this position isn't chosen anymore.
So every time it choses a matrixposition, the number on that position goes down with 1 until all positions are 0.
One problem that I stumble upon is that the count down stops when one position is zero, while I want to make it stop when all the positions are zero.
Until now I have this code;
countmatrix = ones(3,4)*20 % makes matrix with all 20
while (position ~= 0)
for i =1:1
a = randi(3); % Chooses random row
b = randi(4); % Chooses random column
position = countmatrix(a,b) % Picks position in matrix with a and b
position2 = position - 1; % Substracts position with one, and adds in new variable
countmatrix(a,b) = position2; % New variable is put in the matrix
end
end

Respuestas (1)

Mathieu NOE
Mathieu NOE el 9 de Nov. de 2020
hello
simple code
pause to let you observe the evolution of the matrix in the command window
n = 3;
m = 5;
A = rand(n,m);
rand_vector = randperm(n*m); % generate a random vector that will "pick" one random cell of the matrix and give it a new value
for ci = 1:n*m
ind2pick = rand_vector(ci);
A(ind2pick) = 1 % NB : linear indexing method
pause(1)
end

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by