Reputation: 13
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.
Upvotes: 1
Views: 54157
Reputation: 26040
Your primary error is that you are assigning a floating point value to k1,k2
instead of to k1(i),k2(i)
. In the next step where you access the array elements with index i=2
, the modified k
are still numbers, which Matlab seems to interpret as array of length 1
. You can test this by printing i
at the start of the loop as debug output.
Your next problem is that you do the steps of the Heun method in the wrong order. While it is often found in text books, a tradition that dates back to Heun and Kutta, that the formula for the next value is printed first, with the details of the stages after that, in computing them you need the stages first to then insert their values into the step formula.
Then yet another problem is that you treat y
like the time. However, you have a second order equation, with v=y'
and v'=y''
. You can either treat it as vector valued first-order system, or you need k
values for v
and y
.
y = zeros(1,n+1);
v = zeros(1,n+1);
for i = 1:n
k1y = h*v(i);
k1v = h*f(v(i),y(i));
k2y = h*(v(i)+k1v)
k2v = h*f(v(i)+k1v,y(i)+k1y);
y(i+1)=y(i)+0.5*(k1y+k2y);
v(i+1)=v(i)+0.5*(k1v+k2v);
end
Upvotes: 1
Reputation: 8459
"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.
Upvotes: 0