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 CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by