Search code examples
matlabnumerical-methodsode

I keep getting an error trying implementing midpoint method solving ODE


I am trying to implement Midpoint formulas y[n+1/2] = y[n] + h/2 f (x[n], y[n]) and y[n+1] = y[n] + h *f (x[n] + h/2, y[n + 1/2])

enter image description here

so it solves ODE using midpoint method.

My function is

function [ x, y ] = Midpoint_ODE ( f, xRange, yInitial, numSteps ) 
  % f = name of file with function
  % xrange Interval
  % x(1) first meaning of x
  % x(2) second meaning of x
  x=zeros(numSteps+1,1);
  x(1) = xRange(1);
  h = ( xRange(2) - xRange(1) ) / numSteps; % calculated step size
  y(1,:) = transpose(yInitial);
  for n = 1 : numSteps
    y(n+0.5,:)= (y(n) + (h * 0.5)*(transpose(feval( f, x(n), y(n)))));
    y(n+1,:) = y(n,:) + h * transpose(feval(f, x(n)+ (h/2), y(n+0.5,:))); %evaluating the function
end

But I get an error :

**Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in Midpoint_ODE (line 11)Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in Midpoint_ODE (line 11)** 

I checked it a couple of times, and can't get what's wrong and if I missed some logical piece.


Solution

  • You do not need to keep the half-step value. Thus the easiest is to not have in in the list of values

      for n = 1 : numSteps
        yhalfstep = (y(n,:) + (h * 0.5)*(transpose(feval( f, x(n), y(n,:)))));
        y(n+1,:) = y(n,:) + h * transpose(feval( x(n)+ (h/2), yhalfstep)); 
      end
    

    Also remember that in matlab and similar, a single-index access to a multi-dimensional array gives back the element of the flattened array (column first). That is, in a=[ 1,2;3,4;5,6] you get from a(3) the number 5 as the 3rd element in the first column, while a(3,:) gives the 3rd row [5,6].