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
end

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:

fzero('myfunc',1.0)

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

or,

quad('myfunc',0.0,1.0)

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
end

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:

c=2;
quad(@(x) myfunc(x,c), 0, 1.0)

or,

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.


3 comments:

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!