Search code examples
matlaboctavesimplificationrandom-walk

Random Walk, simplifying the code


I am currently practicing modelling "random walks" and population modelling. I have a working code that works for a 1D random walk, in the future I'd like to add extra dimensions and I think the code I have at the moment would make it more difficult. I need to plot the first two positions before I can start the for loop. Ideally I would like to get rid of that issue and have it start from the first step.

numjumps = 20; %number of steps
R = 0.5; %probability of step to right
more off
prev_position = [0 0]; %first position
x = rand(1); %generate random number 0-1
if x >= R;
  step = 1; %take a step to the right
elseif x < R
  step = -1; %take a step to the left
end

position = [1 prev_position(2) + step];

close all;
figure;
hold on;

plot([prev_position(1) position(1)], [prev_position(2) position(2)]);
axis([0 numjumps -5 5])
for i = (2:numjumps);
  prev_position(i) = position(i-1);
  x = rand(1); %generate random number 0-1
  if x >= R;
    step = 1; %take a step to the right
  elseif x < R
    step = -1; %take a step to the left
  end
  position(i) = [prev_position(i) + step]; %add step to position
  plot(position);
  axis([0 numjumps -5 5])
end

total = sum(position);
mean_position = total/numjumps;
disp(mean_position);

Any help would be greatly appreciated.


Solution

  • You shouldn't use a for loop, just vectorize your code:

    numjumps = 20; %number of steps
    R = 0.5; %probability of step to right
    x = rand (numjumps, 1);
    step = 2 * (x >= R) - 1;
    position = [0; cumsum(step)];
    plot (position)
    

    now it's easy to make it 2D:

    numjumps = 200; %number of steps
    R = 0.5; %probability of step to right
    x = rand (numjumps, 2);
    step = 2 * (x >= R) - 1;
    position = [0, 0; cumsum(step)];
    plot (position(:, 1), position (:, 2))
    

    gives

    enter image description here