Info

This question is closed. Reopen it to edit or answer.

I have a zero matrix with a square of zeros near the middle. I want them to move randomly throughout the matrix.

1 view (last 30 days)
I have a zero matrix with a square of 1's in the middle. I want one of the 1's to be picked randomly then moved in a random direction. (Up, down, left or right.) At the moment it only picks one and moves that one through the iterations. I cant figure out how to get it to randomly pick a new (1) each time and move that randomly. Also another problem i am having is that when a 1 meets another 1 one of them dissapears when it moves again. How can i fix this? Any help would be much appreciated. Here is my code below.
clear; clc
n = 50
A = zeros(n, n);
a = 23, 27;
b = 23, 27;
C = 1;
A(23:27, 23:27) = C;
i = 1
while (i < 1000)
rng = randi(4);
i = i + 1;
if rng == 1 && a ~= 1;
A(a, b) = 0;
A(a - 1, b) = 1;
a = a - 1;
elseif rng == 2 && b ~= 1;
A(a, b) = 0;
A(a, b - 1) = 1;
a = a;
b = b - 1;
elseif rng == 3 && b <= n;
A(a, b) = 0;
A(a + 1, b) = 1;
a = a + 1;
b = b;
else if rng == 4 && a <= n;
A(a, b) = 0;
A(a, b + 1) = 1;
b = b + 1;
end
end
end
A
a
b
pcolor(A)

Answers (1)

Sonam Gupta
Sonam Gupta on 6 Nov 2017
I think that you need to change the logic. In your code, only the direction is getting chosen randomly. The element should also be chosen randomly. As well as in one iteration after moving a '1', it will be replaced with zero. So the 1's will soon spread across the matrix in few iterations. So, it will be a good idea to think along the following line:
1. find the coordinates of non-zero elements in the matrix.
2. pick one of the co-ordinate randomly from above set.
3. Choose a random direction and move in that direction.
Hope this helps.

Community Treasure Hunt

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

Start Hunting!