How can you randomly pick a position in a matrix and make it count down?
조회 수: 3 (최근 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
댓글 수: 0
답변 (1개)
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!