JulianAngussmith
JulianAngussmith

Reputation: 75

Using Matlab to solve a system of ODEs using Euler's method

I have created a function Euler.m to solve a a system of ODEs using Euler's method. I wish to use this function to solve the system of ODEs defined by the anonymous function func=@(t) ([x(t)+4*y(t)-exp(t);x(t)+y(t)+2*exp(t)]) with initial conditions given by y0.

func=@(t) ([x(t)+4*y(t)-exp(t);x(t)+y(t)+2*exp(t)]);
y0=[4;5/4];
y_exact=@(t) [4*exp(3*t)+2*exp(-t)-2*exp(t);2*exp(3*t)-exp(-t)+exp(t)/4]; %exact solution of ODEs
a=0; % such that 
b=1; % a<t<b
N=120;
[t,y] = Euler(func,a,b,y0,N)

However, the following error is displayed:

"Error using solution>@(t)([x(t)+4*y(t)-exp(t);x(t)+y(t)+2*exp(t)]) Too many input arguments.

Error in solution (line 7) [t,y] = Euler(func,a,b,y0,N)".

Why is this error being displayed?

Upvotes: 2

Views: 509

Answers (1)

Lutz Lehmann
Lutz Lehmann

Reputation: 25982

You are pretending that you already know when writing the ODE function func what the solutions x(t),y(t) are. Then you are going to compute solutions approximations for it. This is completely the wrong way around.

The function for the right side is just for a point in phase space, so you need

func=@(t,y) ([y(1)+4*y(2)-exp(t);y(1)+y(2)+2*exp(t)]);

where the input y is a two-component vector.

Upvotes: 2

Related Questions