How to make a function recursive in a specific position?

2 views (last 30 days)
I think that the best way to say what I mean is through an example.
Suppose I have a function:
y = my_func(X, n);
I want to perform the following task:
y = my_func(my_func(my_func(X, 1), 2), 3);
I wish to execute this function something like that:
y = a_wonderful_func(@my_func, 1, X, 1:3);
  1. The first argument is a function handle.
  2. The second argument indicates which argument of the function handle is made recursively.
  3. The leftover arguments go to the function handle. Obviously, the recursive position takes just one option as it is feedback to itself.
PS: I don't want to modify my_func. It is desirable that a_wonderful_func be a built-in function.

Answers (1)

Bjorn Gustavsson
Bjorn Gustavsson on 4 Aug 2021
You should have a good look at the functional-programming-constructs toolbox on the file exchange - it shows an example of how to do this (or close enough, illustrating this type of recursion on the Fibonacci-sequence). There are another functional programming package as well: functional-library. I don't work with these tools so cannot honestly recommend one over the other - you have the motivation to find out, I'm sure.
HTH

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!