Help with Euler's Method in Matlab

  1. Nov 6, 2010 #1
    1. The problem statement, all variables and given/known data
    Well, I'm having problems with this script, I'm taking my first course on differential equations, and I am trying to write a script that approximates the values of the solution of a differential equation, and compares them to the exact solution using a table of values, it must also calculate the error, the problem is that I cannot make the table to appear using a column for each variable, instead, the values are spread horizontally and everything is pretty messed up, Its the first time I use Matlab and I might have a lot more mistakes, can anyone help me?

    2. Relevant equations
    the equations are pretty simple, they are in the bottom of the script I wrote

    3. The attempt at a solution
    this is what I wrote

    function [t P] = Euler(t0,P0,L,N) % Nombrando la función y estableciendo los datos necesarios

    Close all;
    h=L./N; % estableciendo tamaño de paso
    t=[]; P=[]; % t y P son vectores vacíos
    P(1)=P0+h.*f(t0, P0); % Estableciendo los primeros componentes de t y P

    for n=1:N-1
    P(n+1)=P(n)+(h.*(f(t(n), P(n))));

    Pexacta= SolucionExacta(t);

    % Para imprimir la tabla

    fprintf(' t Paproximada Pexacta error \n');
    fprintf( '%10.5f %10.5f %10.5f %10.5f', t ,Paprox, Pexacta, error);

    % Para graficar

    hold on
    plot(t, error);

    function ret=f(t,P)%para insertar la ecuación diferencial que deseamos resolver por aproximación


    function f=SolucionExacta(t) % Para establecer la solución aproximada y hacer comparación


  2. jcsd
  3. Nov 6, 2010 #2
    The issue is you're printing arrays. You need to write your print statement in a loop, looping your values.
  4. Nov 6, 2010 #3
    As viscousflow said you'll need a for loop to print the array. Might help to add a 'next line' command into your code \n


    fprintf( '%10.5f %10.5f %10.5f %10.5f \n', t ,Paprox, Pexacta, error);
  5. Nov 6, 2010 #4
    It worked!, thanks a lot
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Similar Discussions: Help with Euler's Method in Matlab
  1. Matlab Help Euler method (Replies: 10)

  2. Euler's method/matlab (Replies: 2)

  3. Euler's Method (Replies: 0)