How can I simulate a hiker who goes in a different direction every time?
1 view (last 30 days)
I must write a MATLAB program where a hiker walks in different direction every time. The directions are (N,NW,W,SW,S,SE,E,NE) and the length of his steps are 1 for (N,W,S,E) and sqrt(2) for the others. I also must also draw the path in 3D. My problem is that I do not know how I can use the length. In my code the hiker walks in the same radius but actually he must keep walking.
I hope you can help me.
S = randi(8);
Voss on 23 Nov 2021
The idea is that you have to add the new x and y steps to the previous position each time through the loop.
Change your for line to this:
And change your xx(k) and yy(k) assignment lines to this:
This way the first position is at the origin (0,0) and each step is added to the previous position to create a path.
More Answers (1)
Image Analyst on 24 Nov 2021
Edited: Image Analyst on 24 Nov 2021
You don't need to define the directions like that. All you need to do is to get a deltax of +/- 1, and same for y, and for z if you want to move in 3-D. You can use randi([-1, 1], 1) for that.
For what it's worth, I'm also attaching several of my random walk demos that do different things.
% Demo by Image Analyst
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
fontSize = 15;
numSteps = 30;
x = zeros(1, numSteps)
y = zeros(1, numSteps);
z = zeros(1, numSteps);
% Label starting point.
text(x(1), y(1), '1', 'Color', 'r', 'FontSize', fontSize)
for k = 2 : numSteps
% Get delta x, y, and z.
deltax = randi([-1, 1], 1);
deltay = randi([-1, 1], 1);
deltaz = randi([-1, 1], 1);
% Add this onto the last point to get a new point location.
x(k) = x(k-1) + deltax;
y(k) = y(k-1) + deltay;
z(k) = z(k-1) + deltaz;
% Plot it.
plot3(x(1:k), y(1:k), z(1:k), 'b.-', 'MarkerSize', 20, 'LineWidth', 2);
text(x(k), y(k), z(k), [' ', num2str(k)], 'Color', 'r', 'FontSize', fontSize)
% Compute the distances from the origin.
distances = sqrt(x .^ 2 + y .^ 2)
maxDistance = max(distances)
What you have to do (to modify the code) is to check the delta's and make sure they are not the same as the delta's from the prior step. If they are all 3 the same, then he's walking in the same direction as last time. Since that's not allowed you'd have to get a new set of delta's and check again.