How to convert a string to a function?

조회 수: 10 (최근 30일)
Todd Wilson
Todd Wilson 2017년 10월 12일
편집: Cedric 2017년 10월 12일
Hello. How would you convert a string to a function? For example: function [y] = equation(x,exp_or_sin) if x=1 and under function I have a statement such as y = exp_or_sin(x), this is wrong I know. and when using the function equation(1,"exp"). Here, I am trying to say that any function such as "exp" or "sin" can be converted to sin(x) or exp(x) and have an equation like exp(x) and when x=1, y would be y=exp(1).

채택된 답변

Cedric
Cedric 2017년 10월 12일
편집: Cedric 2017년 10월 12일
doc str2func
but unless you know what you are doing (or you are just playing to see how that works), approaches that rely on converting a string to a function are often flawed (*).
Anyhow, note that you could allow users to pass a function handle instead of a string or char variable:
function plot_on_01( func )
x = 0 : 0.1 : 1 ;
plot( x, func(x) ) ;
grid on ;
end
can be called as follows:
plot_on_01( @sin )
plot_on_01( @cos )
plot_on_01( @sqrt )
plot_on_01( @exp )
plot_on_01( @(x)log10(1+x) )
Note (*): I am using STR2FUNC for example when I am building test suites for large projects, but otherwise it is very rare.

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by