9.7: What Could Go Wrong?
- Page ID
- 84733
Don’t forget the @
on the function handle. If you leave it out, like:
[T, Y] = ode45(rate_func, [0, 365], 1000)
MATLAB treats the first argument as a function call and calls rate_func
without providing arguments. Then you get an error message:
Not enough input arguments.
Error in rats>rate_func (line 18)
res = a * y * (1 - cos(omega * t));
Error in rats (line 6)
[T, Y] = ode45(rate_func, [0, 365], 1000);
Also, the rate function you write has to take two input variables, t
and y
, in that order, and return one output variable, res
.
If you’re working with a rate function like:
\[\frac{dy}{dt}(t) = a y(t)\notag\]
you might be tempted to write this:
function res = rate_func(y) % WRONG
a = 0.002;
res = a * y;
end
But that would be wrong. So very wrong. Why? Because when ode45
calls rate_func
, it provides two arguments. If you only take one input variable, you’ll get an error. So you have to write a function that takes t
as an input variable, even if you don’t use it:
function res = rate_func(t, y) % RIGHT
a = 0.002;
res = a * y;
end
Another common error is to write a function that doesn’t make an assignment to the output variable. If you write something like:
function res = rate_func(t, y)
a = 0.002;
omega = 2*pi / 365;
r = a * y * (1 - cos(omega * t)); % WRONG
end
and then call it from ode45
, you get
Output argument "res" (and maybe others) not assigned during call
to "rate_func".
I hope these warnings save you some time debugging.