How can I convert handle function to a string

I need to convert handle function to string to passed it to function solve which taken string expression the handle function is some thing like
f=@(x) 2*x+1
I tried >>func2str(f) and then solve(f)
but I get an error

1 Kommentar

Obviously note - Quite a late response.
Idk which version of MATLAB you were or are using, but in the newer versions you can try this -
f=@(x) 2*x+1
f = function_handle with value:
@(x)2*x+1
eqn = str2sym(func2str(f))
eqn = 
solve(eqn)
ans = 
Also, if it is a function of a single independent variable, you can use fzero

Melden Sie sich an, um zu kommentieren.

Antworten (3)

f=@(x) 2*x+1
f = function_handle with value:
@(x)2*x+1
syms x
solve(f(x))
ans = 
Arnaud Miege
Arnaud Miege am 1 Jun. 2011

0 Stimmen

You can do char(f) but I don't think this will work with solve, unless you remove the '@x' from the string.
Arnaud

5 Kommentare

Yes, Eman's difficulty (shown in another thread) is in failing to strip out the '@(x)' -- code that Oleg (I think it was) already provided.
so how can I remove @(x) from the function
believe me oleg code doesn't work with me
Matt Fig
Matt Fig am 1 Jun. 2011
f=@(x) 2*x+1;
str = strrep(char(f),'@(x)','')
Oleg Komarov
Oleg Komarov am 1 Jun. 2011
@Eman: then provide the whole code that fails with the solution I proposed

Melden Sie sich an, um zu kommentieren.

Marco Cordero
Marco Cordero am 8 Nov. 2023

0 Stimmen

This is way way too late to answer but for anyone searching for answers that stumbled upon this question, you might want to try the inline function. As of today, its usage it's no longer recommended and anonymous functions are the preferred method, however, it might come in handy regardless of this.

1 Kommentar

Um, inline is so old. It has been deprecated, and will probably disappear one day. inline functions are very slow. MUCH slower than a function handle. Since a function handle will work, as long as you understand them, there is no need for an inline function, unless you are stuck with a 20 year old release of MATLAB.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Function Creation finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 1 Jun. 2011

Kommentiert:

am 8 Nov. 2023

Community Treasure Hunt

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

Start Hunting!

Translated by