Moving in an Array, Relative Location/Origin

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.

回答(1 个)

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 个评论

Yes, it is essentially a random walk.
Did you run my code?
Does it do what you want it to?

请先登录,再进行评论。

类别

帮助中心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!

Translated by