Effacer les filtres
Effacer les filtres

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

6 vues (au cours des 30 derniers jours)
Charly
Charly le 6 Mar 2014
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

Réponse acceptée

Mehmet OZC
Mehmet OZC le 6 Mar 2014
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 commentaire
per isakson
per isakson le 6 Mar 2014
Modifié(e) : per isakson le 7 Mar 2014
To suppress the output to the screen, replace
type(x)
by
evalc( 'type( ''x'' )' );

Connectez-vous pour commenter.

Plus de réponses (3)

Walter Roberson
Walter Roberson le 6 Mar 2014
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 commentaires
Walter Roberson
Walter Roberson le 6 Mar 2014
Elegant is not what I would call it ;-)
per isakson
per isakson le 7 Mar 2014
Modifié(e) : per isakson le 7 Mar 2014
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

Connectez-vous pour commenter.


Charly
Charly le 6 Mar 2014
Thank you for your answers
  1 commentaire
Jos (10584)
Jos (10584) le 6 Mar 2014
This will also work for non-functions, like text files etc ...

Connectez-vous pour commenter.


Jos (10584)
Jos (10584) le 7 Mar 2014
FYI, I just upload my function ISFUNCTION to the File Exchange:

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by