MATLAB: How to pass an argument for a function when it is an argument in another function

argumentmatlab function

I would like to pass a function to another function, but with a parameter for it to use. for example, I have written a cobweb function to plot a cobweb of an iterative series function. It takes a function as an argument. eg. cobweb(@sin, x0, [0 1.5 0 1.5], max_iter) returns a cobweb plot like below for repeated sin function.
However, I want to pass another function I've written, an iterative map
function x1 = it_map(x0, r)
x1 = r*x0*(1-x0);
however to do this using the same code, I'd need to pass this function in with its own argument (r), and I can't see anyway to do that.
Is there anyway to do this? or should I just fix the argument as r in the code, which is fiddly..

Best Answer

If r is definied beforehand you can create a function handle that turns your 2-argument function into a 1-argument function e.g.
r = 7;
f = @( x0 ) it_map( x0, r );
Then you can pass f to your cobweb function in the same way as sin because it is a function of just the one argument. This works so long as r is known before you create the function handle.
cobweb(f, x0, [0 1.5 0 1.5], max_iter)
This is a very useful 'trick' to know when you pass function handles around - the idea that you can have arguments that are 'bound' into the function at definition time and arguments that are variable to be passed in a calling time.
It means you can always change a function of n arguments into a function of < n ( or > n I suppose in the inverse case) arguments so long as you know some of them at function handle definition time.