Index exceeds matrix dimensions error for summation
Información
La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.
Mostrar comentarios más antiguos
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 comentario
Michael Ballenger
el 26 de Nov. de 2018
Respuestas (1)
madhan ravi
el 26 de Nov. de 2018
0 votos
You get an error becuase sp2 is a scalar which is 0 and you didn't increment it inside the loop
3 comentarios
Michael Ballenger
el 26 de Nov. de 2018
Michael Ballenger
el 26 de Nov. de 2018
madhan ravi
el 26 de Nov. de 2018
Editada: madhan ravi
el 26 de Nov. de 2018
Anytime :)
La pregunta está cerrada.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!