Input's control to check if is a function

조회 수: 14 (최근 30일)
Samuele Botticelli
Samuele Botticelli 2020년 10월 26일
편집: Walter Roberson 2023년 4월 24일
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)

채택된 답변

Walter Roberson
Walter Roberson 2020년 10월 26일
편집: Walter Roberson 2023년 4월 24일
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
Walter Roberson
Walter Roberson 2020년 10월 26일
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 2023년 4월 24일
편집: Walter Roberson 2023년 4월 24일
if you use functions() on the handle, then the result will have type: 'anonymous' or 'type', 'simple' or 'scopedfunction' or 'nested'

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by