Input's control to check if is a function
14 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Samuele Botticelli
le 26 Oct 2020
Modifié(e) : Walter Roberson
le 24 Avr 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)
0 commentaires
Réponse acceptée
Walter Roberson
le 26 Oct 2020
Modifié(e) : Walter Roberson
le 24 Avr 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 commentaires
Walter Roberson
le 26 Oct 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
le 24 Avr 2023
Modifié(e) : Walter Roberson
le 24 Avr 2023
if you use functions() on the handle, then the result will have type: 'anonymous' or 'type', 'simple' or 'scopedfunction' or 'nested'
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!