How to convert variables in a function handle ?

13 views (last 30 days)
Hi all,
Is It possible to convert this handle function
f = @(x1,x2,x3) [g1;g2;g3];
where g1 g2 and g3 are complicated functions that depends on x1 x2 and x3, in something like that ?
ff = @(x) [g11;g22;g33];
g11 g22 g33 depends on x(1) x(2) and x(3) ...... so instead of having 3 variable x1 , x2 , x3 ....I would like to have x(1), x(2), x(3).
( example : g1 = x1*x2 - x3 becomes --> g11 = x(1)*x(2) - x(3) )
Note that:
The function f comes from some calculus and so, I cannot modify.
Thank you guys!

Answers (1)

John D'Errico
John D'Errico on 2 Apr 2022
Edited: John D'Errico on 2 Apr 2022
Um, not easily, and yes, sort of.
If you want to actually modify the function handle, then that would take some effort and text processing using find and replace. And that would be a pain in the neck. But it is entirely do-able I would think, yet not worth the effort, since at the same time, it is quite easy to just wrap your function handle inside another. So if you have this:
f = @(x1,x2,x3) [g1;g2;g3];
then just do this:
ff = @(x) f(x(1),x(2),x(3));
The new function handle will effectively split x apart into three separate variables, which then get passed into the original function handle f. So nothing involving find and replace is necessary because the wrapper handles all the work.
In the future, I would strongly suggest learning to use vectors in the first place instead of numbered variable names. MATLAB is a language that is at its best when it is used with vectors and arrays. What you claimed was absolutely necessary was probably not truly necessary. In this case it is easily fixed though.

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!