Index exceeds matrix dimensions error for summation

A project Im working on is a random step program with varying steps. We need to know the final step at the end, my code keeps giving me an error for index exceeds the matrix dimensions. My first two sections run perfect and give me what I need, but as I increase the steps it gives me the error. Please help me debug!
%% Part 1 - Random Walk
% Using a similar program to odds vs evens, set initial conditions
walkerL = 1 ;
walkerR = -1 ; % Giving the walker place to walk
x1 = 0.5 ; % probability walker will step right
x2 = -0.5 ; % probability walker will step left
for i = 1:1000
sp(1) = 0 ; % starting point
step = rand(1) ; % Generate a random number
if step<x1 % if step is less than probability, then
X = walkerR ; % walker takes a step right
else
X = walkerL ; % walker takes a step left
end
sp(i+1) = sp(i) + X ; % dictates the move
end
comet((0:1000),sp) ;
title('Random Walk')
xlabel('Number of Steps')
ylabel('Left Step(+) vs Right Step(-)')
%% Part 2 - Random Walk Ensemble
% In the foloowing sections the random walk will be run 5 different times with
% varying number of steps
%% 1000 steps
walkerL = 1 ;
walkerR = -1 ;
x1 = 0.5 ;
x2 = -0.5 ;
for i = 1:1000
sp(1) = 0 ;
step = rand(1) ;
if step<x1
X = walkerR ;
else
X = walkerL ;
end
sp(i+1) = sp(i) + X ;
end
stepfinal1000 = sp(i+1); % determines final step
%% 2000 steps
walkerL2 = 1 ;
walkerR2 = -1 ;
x3 = 0.5 ;
x4 = -0.5 ;
for i2 = 1:2000
sp2(1) = 0 ;
step2 = rand(1) ;
if step2<x3
X2 = walkerR2 ;
else
X2 = walkerL2 ;
end
sp(i2+1) = sp(i2) + X2 ;
end
stepfinal2000 = sp2(i2+1); %% here is where my issue is

1 Comment

I'm supposed to continue through 10000, 20000, 100000, and 1000000 steps so a fix to help me with all of these would be great. And I have to create a histogram with my final steps from each program.

Answers (1)

You get an error becuase sp2 is a scalar which is 0 and you didn't increment it inside the loop

3 Comments

I found my error, I had incremented sp2 I just hadn't fully labeled the summation inside the loop correctly. I had sp(i2+1) = sp(i2) +X2 when it should have been sp2(i2+1)=sp2(i2)+X2
Thanks for the advice though
Anytime :)

This question is closed.

Asked:

on 26 Nov 2018

Closed:

on 20 Aug 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!