2

I am a little confused as to when to use ode45(@functionname, tspan, initialvalues,...) or ode45('functionname', tspan, initial values,...). I have seen examples using both but sometimes one works and the other doesn't.

e.g. [t,y]=ode45(@MM2, tspan, y0,[],k1,k2,k3) works, but [t,y]=ode45('MM2', tspan, y0,[],k1,k2,k3) doesn't.

Many thanks in advance.

Richard
  • 21
  • 1
  • 3
    Reading the documentation (`help ode45` or `doc ode45`) is the usual way to answer such questions. There's a lot of old code still floating around online. Specifying function with strings was deprecated many years ago (though it still works). Using a function handle is more robust and yields faster code. – horchler Apr 10 '16 at 20:39
  • The only context I've encountered where a string fails in that use case is when the function, in this case `MM2`, is a local or nested function such that `feval` can't find it. My advice, if you can, always use function handles. String execution is a legacy feature. – TroyHaskin Apr 11 '16 at 00:15

1 Answers1

0

As I have understood, you will use "@" when the function you are going to integrate is in another text file. If the function is in the same text file, you don't need to use "@".

For example: let's calculate the horizontal coordinate of a Van Der Pol pendulum.

In file 1: xdot_van_der_pol.m

function dxdt = xdot_van_der_pol(t, x)
global u;
if size(u,1) == 0
    u = 1
end
dx1 = x(2);
dx2 = u*(1 - x(1)^2)*x(2) - x(1);
dxdt = [ dx1 ; dx2 ];

In file 2: integration.m

u = 1;
tf = 20;
xo = [2 ; 0];
[t,x]=ode45(@xdot_van_der_pol, [0 tf], xo);
subplot(221); plot(x(:,1), t(:,1)); hold on;
subplot(224); plot(t(:,1), x(:,2)); hold on;
subplot(223); plot(x(:,1), x(:,2)); hold on;

Another case would be to write everything in the same text file, so you wouldn't have to use "@" to call the function.