MATLAB Answers

0

call functions with same name

Asked by 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

  0 Comments

Sign in to comment.

2 Answers

Jan
Answer by 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 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
Answer by 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);

  0 Comments

Sign in to comment.