Search code examples
matlabdifferential-equations

Implementing Euler's method for solving differential equations


This code is to find the Euler's method on MATLAB

function [x,y]=euler_forward(f,xinit,yinit,xfinal,n)

h=(xfinal-xinit)/n;
% Initialization of x and y as column vectors
x=[xinit zeros(1,n)]; y=[yinit zeros(1,n)];
% Calculation of x and y
for i=1:n
x(i+1)=x(i)+h;
y(i+1)=y(i)+h*f(x(i),y(i));
end
end`
'f=@(x,y) (1+2*x)*sqrt(y);
% Calculate exact solution
g=@(x,y) (1+2*x)*sqrt(y);
xe=[0:0.01:1];
ye=g(xe);
[x1,y1]=euler_forward(f,0,1,1,4);

% Plot
plot(xe,ye,'k-',x1,y1,'k-.')
xlabel('x')
ylabel('y')
legend('Analytical','Forward')
% Estimate errors
error1=['Forward error: ' num2str(-100*(ye(end)-y1(end))/ye(end)) '%'];

error={error1}

So I have this so far for the problem and the it gives an error saying y is not defined. What do I do?


Solution

  • The problem is here:

    % Calculate exact solution
    g=@(x,y) (1+2*x)*sqrt(y);
    

    Exact solution is a function of one variable, x. Presumably, you were supposed to find it with paper and pencil (or with Wolfram Alpha, etc): it is

     g=@(x) .25*(x.^2+x+2).^2 
    

    Then the code works as expected, producing this neat chart: as is typical for Euler's method, the numerical solution lags behind the exact one.

    output