Function having string as argument

3 visualizaciones (últimos 30 días)
Mitul Gpoani
Mitul Gpoani el 11 de Abr. de 2019
Editada: Stephen23 el 11 de Abr. de 2019
Hi there,
I am making a function called 'derr' which calculates derivative of the function given in the argument as string.
function = derr('name of function');
example if 'sin' is given as argument this function should calculate derivative of sin.
calling of function should be like : derr('sin')
How can I do that?
Thank you.

Respuesta aceptada

Stephen23
Stephen23 el 11 de Abr. de 2019
Editada: Stephen23 el 11 de Abr. de 2019
I would not recommend using a string to define the input function.
A much more reliable way would be to write your code to accept a function handle (which is the correct variable type for holding functions):
For example, define your function something like this:
function out = myfun(fun)
assert(isa(fun,'function_handle'),'Input must be a function handle')
out = fun(pi); % do whatever you want with the function handle...
end
and then simply call your function using any function handle:
myfun(@sin)
myfun(@cos)
myfun(@sqrt)
myfun(@(n)3*(n.^2))
If you really want to limit the user to using strings (not designed for holding functions) then consider using str2func or switch inside your function.

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by