call functions with same name

29 views (last 30 days)
Mir Milad
Mir Milad on 30 Oct 2011
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

Answers (2)

Jan
Jan on 30 Oct 2011
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 Comment
Mir Milad
Mir Milad on 30 Oct 2011
Thank you for your response.
I use functions with different names and then use str2func function to select one of them by conditions.

Sign in to comment.


Sven
Sven on 30 Oct 2011
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);

Categories

Find more on Function Handles in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!