MATLAB Now it’s your turn. Write a function which takes as input an integer numb
ID: 3888698 • Letter: M
Question
MATLAB
Now it’s your turn. Write a function which takes as input an integer number of steps and performs a random walk of that many steps and returns the sequence of distances from the initial starting position. For example:
>> A = random_walk(10)
A = -1 -2 -3 -4 -3 -4 -5 -6 -7 -6
Note that each element of the array is exactly 1 step away from the previous element. Staying in place is not an option. Neither is taking more than 1 step at a time.
You can make a quick and dirty visualization of this by using the plot function.
>> plot(A)
If you were to count how many times each distance occurred in the array, you would know how many times you occupied each spot.
You can find the unique elements of an array using the unique function.
>> unique(A)
ans =
-7 -6 -5 -4 -3 -2 -1
You can find how many times a value occurs in an array using the length and find functions.
>> length(find(A==-3))
ans =
2
If you were to take a random walk of a given length many times, you would get many different trajectories, that all start from the same place, but all end up in different places, and all visit the locations (distances from start) different numbers of times. You can then find out how far, on average, you end up from the start, and how many times, on average, you visit each location. You can even get an average trajectory.
You can compute average values of a function using a for loop and an aggregator variable:
>> avg = 0;
for i=1:N value = foo(args);
avg = avg + value/N;
end
disp(avg)
To compute average final distance from the start, you will need to do some more processing and manipulation in the loop. Similarly, to compute the average number of times at each distance requires some additional processing. Figuring that part out is up to you.
To keep you motivated (but, probably mostly distract you), you can make a pretty picture:
>> hold on
for i=1:10
A = random_walk(1000);
plot(A);
end
hold off
Challenge: extend this simulation to 2-dimensions (4 choices: up, down, left, right) and visualize the trajectory on a plot. Challenge: instead of limiting your movement to 4 directions, you can now move in any direction. You can generate a random direction as an angle from the x-axis:
angle = rand*2*pi
The new x- and y- coordinates are given by
x = x + cos(angle)
y = y + sin(angle)
Explanation / Answer
Solution:
% function for random walk
function [Aval] = random_walk(n);
%two independent random variables x(n) and y(n)
Aval = [0; cumsum(2*(rand(n,1)>0.5)-1)];
Bval=[0; cumsum(2*(rand(n,1)>0.5)-1)];
% for axis limit
YA = max(abs(Bval))+1;
XA=max(abs(Aval))+1;
%plotting
plot(Aval,Bval);
axis([-XA XA -YA YA]);
%Labeling the plot
title(['2-D Random walk for ' int2str(n) ' steps'] );
xlabel('x(n)');
ylabel('y(n)');
>>A=random_walk(10)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.