How can I convert handle function to a string

조회 수: 39 (최근 30일)
Eman Ahmed Elsayed 2011년 6월 1일
댓글: John D'Errico 2023년 11월 8일
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이전 댓글 -1개 표시이전 댓글 -1개 숨기기
Dyuman Joshi 2023년 11월 8일
편집: Dyuman Joshi 2023년 11월 8일
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

댓글을 달려면 로그인하십시오.

답변 (3개)

Walter Roberson 2023년 11월 8일
f=@(x) 2*x+1
f = function_handle with value:
@(x)2*x+1
syms x
solve(f(x))
ans =
댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

댓글을 달려면 로그인하십시오.

Arnaud Miege 2011년 6월 1일
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이전 댓글 3개 표시이전 댓글 3개 숨기기
Matt Fig 2011년 6월 1일
f=@(x) 2*x+1;
str = strrep(char(f),'@(x)','')
Oleg Komarov 2011년 6월 1일
@Eman: then provide the whole code that fails with the solution I proposed

댓글을 달려면 로그인하십시오.

Marco Cordero 2023년 11월 8일
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이전 댓글 -1개 표시이전 댓글 -1개 숨기기
John D'Errico 2023년 11월 8일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by