Reputation: 169
so I need to create a function that plots location versus time for an individual who makes successive random jumps. Each jump is one unit to the right with probability R, and otherwise its one unit to the left. The arguments need to be R = probably of jumping one unit to the right; a = the initial location; and numjumps = number of jump the individual makes. I also need to use the binornd()
function.
What I've coded so far is:
function plot_sim(a,numjumps,R)
loc = a;
time = 0;
for i = 1:numjumps;
loc = loc + (2*binornd(1,R)-1);
time = time + 1;
hold on;
plot(time,loc,'-')
end
And I have to evaluate it with plot_sim(0,25,0.5)
. And I am just confused because even though I have plot(time,loc,'-')
, it doesn't plot as connecting lines, it just plots as separate dots. I've tried including the plot function outside of the for loop and that doesn't work. I've even tried changing the colours of the dots and that doesn't even work. Am I coding this wrong?
Upvotes: 0
Views: 1409
Reputation: 104483
The solution to your problem is quite simple. When you are plotting lines, you need to have at least two points so that you can draw lines. What you actually need to do is remember the previous position so that at each time step, you can draw a line from the previous position to the current position.
What I would do is first generate a figure that generates one jump and we can draw a line from the initial position to this point. After, then run your loop where we keep track of the previous event, generate your new event at the next time step then draw a line from the previous event at the previous time to the current event at the current time.
Remember, the time is on the horizontal axis and the position is on the vertical axis. As such, the events are saved as a two element vector where the first element is time, and the second element is the position.
Therefore, try doing this:
function plot_sim(a,numjumps,R)
%// Keep the previous event
%// x coordinate is time
%// y coordinate is position
%// Time = 0
prev_loc = [0 a];
%// Generate the next event
%// Time = 1
loc = [1 prev_loc(2) + 2*binornd(1,R)-1];
%// Close all figures then open up a new one
close all;
figure;
hold on;
%// Plot a line from the previous position to the current one
plot([prev_loc(1) loc(1)], [prev_loc(2) loc(2)]);
%// For each new position...
for i = 2:numjumps
%// Remember the previous position
prev_loc = loc;
%// Generate the next position
loc = [i prev_loc(2) + (2*binornd(1,R)-1)];
%// Plot the position
plot([prev_loc(1) loc(1)], [prev_loc(2) loc(2)]);
end
Here's what I get when I try running it with plot_sim(0.25,10,0.25)
, so a = 0.25, numjumps = 10, R = 0.25
:
Remember, you may not get the same plot I do because it's random. Every time you run this function, you should get a different random walk and that's what we expect.
Upvotes: 2