How to replace variable name in function handle?

4 Ansichten (letzte 30 Tage)
Kalore Shubham Arun
Kalore Shubham Arun am 25 Feb. 2019
Kommentiert: Marco Aurélio am 9 Jul. 2024
I have a function handle as given below
f = @(x1,x2) x1*x2
and I want to change variable name to
f = @(x) x(1)*x(2)
Please help me
Thanks
PS: The function is just for illustration purpose
  1 Kommentar
Marco Aurélio
Marco Aurélio am 9 Jul. 2024
Hello Matlab mate.
I think you must redefine de function handle just rewriting like this:
f=@(x) prod(x);

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephan
Stephan am 25 Feb. 2019
Bearbeitet: Stephan am 25 Feb. 2019
Hi,
for me this worked:
f = @(x1,x2) x1*x2
f = string(char(f));
f = replace(f,"@(x1,x2)","@(x)");
f = replace(f,["x1","x2"],["x(1)","x(2)"]);
f = str2func(f)
result is:
f =
function_handle with value:
@(x1,x2)x1*x2
f =
function_handle with value:
@(x)x(1)*x(2)
Best regards
Stephan
  2 Kommentare
madhan ravi
madhan ravi am 25 Feb. 2019
Bearbeitet: madhan ravi am 25 Feb. 2019
stephen what if there are 100 inputs to the function handle? it would be not a good idea
Stephan
Stephan am 25 Feb. 2019
Bearbeitet: Stephan am 25 Feb. 2019
You are right. But i think this function is worth to be shown here as an alternative for small examples. Maybe it is not the best / most efficient solution here. Yours is pretty nice - but the OP asked for how to replace variable names in a function handle - this is what i was answering to.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

madhan ravi
madhan ravi am 25 Feb. 2019
Instead of converting it to your later need convert the vector as comma separated list using num2cell():
x=rand(1,2); % example vector
X=num2cell(x);
f(X{:}) % pass the vector all at once

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by