필터 지우기
필터 지우기

How to know if a string is a valid matlab function ?

조회 수: 6 (최근 30일)
Charly
Charly 2014년 3월 6일
답변: Jos (10584) 2014년 3월 7일
Hi,
I'm looking for a function which can tell me if a string is a valid matlab function.
For exemple :
function_i_m_looking_for('sin'); % should return 1
function_i_m_looking_for('toto'); % should return 0
Thank you

채택된 답변

Mehmet OZC
Mehmet OZC 2014년 3월 6일
You can simply run the function below, hope it helps.
function output = function_i_m_looking_for(x)
output = 1;
try
type(x)
catch
output = 0;
end
end
  댓글 수: 1
per isakson
per isakson 2014년 3월 6일
편집: per isakson 2014년 3월 7일
To suppress the output to the screen, replace
type(x)
by
evalc( 'type( ''x'' )' );

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

추가 답변 (3개)

Walter Roberson
Walter Roberson 2014년 3월 6일
regexp(x, '^[A-Za-z]\w*$') && ismember(exist(x), [2 3 5 6])
The beginning bit filters out embedded operators and file extensions and directory specifiers that exist() would otherwise pay attention to. 2 would be .m file on your search path, 3 is mex file on search path, 5 is built-in MATLAB function, 6 is .p file on search path. You might also want to include 8 which is class name.
  댓글 수: 3
Walter Roberson
Walter Roberson 2014년 3월 6일
Elegant is not what I would call it ;-)
per isakson
per isakson 2014년 3월 7일
편집: per isakson 2014년 3월 7일
I call it smart, however ...
>> str = '+';
>> regexp( str, '^[A-Za-z]\w*$' )
ans =
[]
>> regexp( str, '^[A-Za-z]\w*$' ) && true
Operands to the || and && operators must be convertible to logical scalar values.
>>
Why isn't there a regular expression function, which returns a logical value?
.
A modified one-liner
>> not(isempty(regexp( str, '^[A-Za-z]\w*$' ))) && true
ans =
0

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


Charly
Charly 2014년 3월 6일
Thank you for your answers
  댓글 수: 1
Jos (10584)
Jos (10584) 2014년 3월 6일
This will also work for non-functions, like text files etc ...

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


Jos (10584)
Jos (10584) 2014년 3월 7일
FYI, I just upload my function ISFUNCTION to the File Exchange:

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by