Index exceeds matrix dimensions error for summation
Info
This question is closed. Reopen it to edit or answer.
Show older comments
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
Michael Ballenger
on 26 Nov 2018
Answers (1)
madhan ravi
on 26 Nov 2018
0 votes
You get an error becuase sp2 is a scalar which is 0 and you didn't increment it inside the loop
3 Comments
Michael Ballenger
on 26 Nov 2018
Michael Ballenger
on 26 Nov 2018
madhan ravi
on 26 Nov 2018
Edited: madhan ravi
on 26 Nov 2018
Anytime :)
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!