Search code examples
matlabmathnumerical-methodsdifferential-equations

Euler's explicit method on MATLAB raises error with example


This is my code for Euler's explicit Method on MATLAB

function [t,x] = meuler(f, intervalo, x0, N)
h = (intervalo(2)-intervalo(1))/N;
t = intervalo(1):h:intervalo(2);
x(:,1) = x0(:);
for i = 1:N
    x(i+1,:) = x(i,:) + h*(f(t(i),x(i,:)));
end

It takes a function f defined in another file. When I try to run the code with the following function

function f = funccorazon(t,x)
f1 = x(2);
f2 = 16*x(1)+4*sin(2*t);
f=[f1;f2];

I get this error

>> meuler(@funccorazon, [0 2*pi], [0 2], 1000)
Attempted to access y(2); index out of bounds because numel(y)=1.

Error in funccorazon (line 2)
f1 = y(2);

and I don't know why. Apparently, when I solve the differential equation using ode45, nothing seems to go wrong. Any help with that would be appreciated. Thank you!


Solution

  • The reason for the error is that you need to work with row vectors instead of column vectors.

    first, in your function call, define the input x0 as row vector:

    meuler(@funccorazon, [0 2*pi], [0,2], 1000)
    

    second, in funccorazon function, define the output f similarly:

    f=[f1,f2];
    

    lastly, in meuler function do the following changes:

    x = zeros(N,2);
    x(1,:) = x0;