call functions with same name

13 ビュー (過去 30 日間)
Mir Milad
Mir Milad 2011 年 10 月 30 日
Hi,
I have 2 m files in different directories with same name. I want call this functions, but by conditions I need select one of them. Is there any way to select one of this 2 functions?
Thank you

回答 (2 件)

Jan
Jan 2011 年 10 月 30 日
Rename the files.
If two M-files have the same name, the one in the current path is preferred. If both are not in the current path, the file occuring earlier in the PATH is chosen.
But then the program flow depends on teh current directory. And this is hard to control, because any subfunction could modify it.
Therefore the only stable solution is to avoid files with equal names.
  1 件のコメント
Mir Milad
Mir Milad 2011 年 10 月 30 日
Thank you for your response.
I use functions with different names and then use str2func function to select one of them by conditions.

サインインしてコメントする。


Sven
Sven 2011 年 10 月 30 日
Keep in mind that there is a more recommended way to accomplish this than using str2func():
Method A: At every location you call either function1() or function2(), depending on whether condition1 is true or not:
myInputArg = 50;
if condition1==true
output = function1(myInputArg);
else
output = function2(myInputArg);
end
Method B: If you don't like having the if/else statement every time you want to call function1/function2, then you can use a function handle once, and it will redirect your call to the right function every time after that:
if condition1==true
funcToBeUsed = @(inArg)function1(inArg);
else
funcToBeUsed = @(inArg)function2(inArg);
end
...
...
output = funcToBeUsed(50);
output = funcToBeUsed(500);

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by