I am fairly new to Matlab and trying to create a Matlab function that applies the modified Euler's method to approximate the solutions of a certain differential equation. When I call the function in the command window I receive the following error:
Index exceeds the number of array elements (1). Error in modified_euler2 (line 10) y(i+1)=y(i)+0.5*(k1(i)+k2(i));
I am calling the function like so and with the below inputs:
modified_euler2(60,1000,9.8,0.1125,1.125,25)
The complete code of the function is below:
function output = modified_euler2(T,n,g,C,K,L)
f = @(v,y) (g - C*abs(v)*v -max(0, K*(y - L)));
h = T / n;
t = 0:h:T;
y = zeros(1,n+1);
v = zeros(1,n+1);
k1 = zeros(1,n+1);
k2 = zeros(1,n+1);
for i = 1:n+1
y(i+1)=y(i)+0.5*(k1(i)+k2(i));
k1 = h*f(v(i),y(i));
k2=h*f(v(i)+h,y(i)+k1(i));
end
output = t,y,v,h
figure
plot(y)
end
Any advice on how to fix this error would be much appreciated.
"Index exceeds the number of array elements" means you are indexing an array with some number n
of elements, but asking for the m
-th elements, where m>n
. So if you had a vector
x = [2 4 6]
then x(1)=2
, but you can't do x(6)
, for example, because x
only has 3 elements.
In your case, Matlab is telling you exactly where the error occurs, in the line
y(i+1)=y(i)+0.5*(k1(i)+k2(i))
You are doing several indexing operations here (y(i+1)
, y(i)
, k1(i)
, and k2(i)
), and one (or more) are causing the error. The problem is that the variable you are trying to index has only one element (Matlab tells you this) but you are asking for the i
-th (or i+1
-th) element, which can't be done unless i=1
.
So you need to identify which of the indexing operations is trying to access an element that doesn't exist.