Input's control to check if is a function

14 visualizaciones (últimos 30 días)
Samuele Botticelli
Samuele Botticelli el 26 de Oct. de 2020
Editada: Walter Roberson el 24 de Abr. de 2023
I'm writing this function:
[x,n_iter,ERR] = newton_fun(f,df,x0,eps,max_iter)
How can I insert an input control that gives me an error if the input "f" is not inserted in the anonymous function form?
es:
>>[x,n_iter,ERR] = newton_fun(@(x)x^2,df,2,0.004,100)

Respuesta aceptada

Walter Roberson
Walter Roberson el 26 de Oct. de 2020
Editada: Walter Roberson el 24 de Abr. de 2023
First you should test
isa(f, 'function_handle')
That will eliminate everything except function handles.
To specifically narrow it down to anonymous functions... I am not sure what the best way is at the moment. I do note, though, that you could use
startsWith(func2str(f), '@')
This would eliminate the case of function handles that are not anonymous functions.
What is your use case for wanting to restrict to anonymous functions? For example why would you want to prevent
[x,n_iter,ERR] = newton_fun(@cos,@(x)-sin(x),2,0.004,100)
and force the user to use
[x,n_iter,ERR] = newton_fun(@(x)cos(x),@(x)-sin(x),2,0.004,100)
??
  3 comentarios
Walter Roberson
Walter Roberson el 26 de Oct. de 2020
if isa(f, 'function_handle') && isa(fd, 'function_handle') && startsWith(func2str(f), '@') && startsWith(func2str(fd), '@')
f and fd are valid
else
f or fd are wrong
end
But this is very likely not what the assignment really wants. What the assignment probably wants is
if isa(f, 'function_handle') && isa(fd, 'function_handle')
without caring whether the function handle is to an anonymous function or not.
Mathworks distinguishes between non-anonymous function handles, @function_name and anonymous functions @(variables)body . It is rare that anything other than the lowest levels need to care whether a given function handle is for an anonymous function or not.
Sure, I have needed to write code that knew the difference, but the context for that was that I was writing a debugging tool that needed to examine anonymous functions to ensure that the functions being invoked were reachable. This is not a common thing for programmers to need to think about.
Walter Roberson
Walter Roberson el 24 de Abr. de 2023
Editada: Walter Roberson el 24 de Abr. de 2023
if you use functions() on the handle, then the result will have type: 'anonymous' or 'type', 'simple' or 'scopedfunction' or 'nested'

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming 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