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

5 次查看(过去 30 天)
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

回答(1 个)

Mathieu NOE
Mathieu NOE 2020-11-9
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by