Tuesday, October 25, 2011

Passing parameters in Matlab or Octave: fzero and quad

Consider a simple function f(x) = 2x written in Matlab/Octave (myfunc.m).

function y = myfunc(x)
    y = 2*x

You could easily use the functions fzero and quad, to find a root of f(x) and the definite integral of f(x) between limits, say "a" and "b".

You would say something like:


where 1.0 is the guessed root. The answer that Matlab finds is indeed zero.



where a=0.0, and b=1.0 are the lower and upper limits. The quad function computes the correct answer (1.0).

Let us say that we had a slightly more general function f(x) = c*x, where "c" is a parameter (c=2, in the previous case). That is, we have the Matlab/Octave function:

function y = myfunc(x,c)
    y = c*x

Quite often we want to use fzero and quad on such a function for a particular setting of "c". That is we would like to be able to pass the parameter "c" to the function.

There are several ways to doing this. Some of them (like making "c" a global variable are ugly). The one I find most convenient is the following:

quad(@(x) myfunc(x,c), 0, 1.0)


quad(@(x) myfunc(x,2.0), 0,1.0)

fzero works in similar fashion. You could say:

fzero(@(x) myfunc(x,2.0), 1.0)

Just to reiterate, this method works in both Matlab and Octave, and you could easily generalize it to passing multiple parameters.


Anonymous said...

Thanks for this entry, that is exactly what I was looking for. :)

Anonymous said...

Ditto: thank you for the quick and clear how-to. Exactly what I needed to refresh my memory!

Sachin Shanbhag said...

You're welcome!