MATLAB Answers

Input's control to check if is a function

3 views (last 30 days)
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?
>>[x,n_iter,ERR] = newton_fun(@(x)x^2,df,2,0.004,100)


Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 26 Oct 2020
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(funcstr(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)


Samuele Botticelli
Samuele Botticelli on 26 Oct 2020
I'll be more clear: It's asking me to write a function "newton_fun" that recive in input a (a rel numer X0, a rel number esp..eccetera) and a fuction "f" and its derivate "df" in the form of "anonymous function". I guess i have to put a control for "f" and "df", but i can't find a way to do it wrintig the function.
Walter Roberson
Walter Roberson on 26 Oct 2020
if isa(f, 'function_handle') && isa(fd, 'function_handle') && startsWith(func2str(f), '@') && startsWith(func2str(fd), '@')
f and fd are valid
f or fd are wrong
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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by