How to pass an argument for a function when it is an argument in another function?
12 views (last 30 days)
Show older comments
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..
0 Comments
Accepted Answer
Adam
on 23 Feb 2018
Edited: Adam
on 23 Feb 2018
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.
More Answers (1)
Guillaume
on 23 Feb 2018
"Is there anyway to do this?"
Yes, it's call argument binding. In matlab, this is achieved by defining an anonymous function:
r = 5;
it_map_bound = @(x0) it_map(x_0, r);
cobweb(it_map_bound, x0, [0 1.5 0 1.5], max_iter);
Note that the anonymous function capture the value of r at creation. Changing r afterward does not affect the anonymous function.
0 Comments
See Also
Categories
Find more on Entering Commands in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!