Moving in an Array, Relative Location/Origin

2 views (last 30 days)
Hello:
I am dealing with arrays that starts off at a location (x,y) on a grid (array) and then moving one space either to the left, right, up, or down. Then, I want to move again using the new coordinate (say, (xo,yo)), so it serves as the new origin. This is similar to doing Monte Carlo simulation. How can I do this using loops under I hit the axes? Thank you.

Answers (1)

Star Strider
Star Strider on 16 Jun 2015
I’m not sure what you want to do, but it seems like a random walk. This should get you started, and you may need to experiment with it to get the result you want:
N = 100; % Size Of Matrix
A = randi(10, N, N); % Create Matrix
X0 = randi(N); % Initial Origin
Y0 = randi(N);
[Ar,Ac] = size(A); % Determine Limits
k1 = 1; % Counter
XY(k1,:) = randi(N, 1, 3); % Initial
while ((X0 > 1) && (X0 < Ac)) && ((Y0 > 1) && (Y0 < Ar))
X0 = X0 + (-1)^randi(2); % New ‘X0’
Y0 = Y0 + (-1)^randi(2); % New ‘Y0’
XY(k1,:) = [X0,Y0,A(X0,Y0)]; % Record Moves & ‘A’ Values
k1 = k1 + 1;
end
figure(1)
plot(XY(:,1), XY(:,2))
grid
axis([1 N 1 N])
  2 Comments
Jack Zhang
Jack Zhang on 16 Jun 2015
Yes, it is essentially a random walk.
Star Strider
Star Strider on 16 Jun 2015
Did you run my code?
Does it do what you want it to?

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!