The naming used here as function1
, Root
, class1
and class2
are just fictitious and does not exist in the code. They are just here to mask their real names, however they explicily represent how the files are disposed on the files system and how they are being called.
Root
, Root/class1
and Root/class2
.Root/class1/function1.m
and Root/class2/function1.m
.function function1( A )
and function function1( A, B )
, respectively.Now I am on the folder Root/class2
running a file called system.m
and I do:
addpath( '../class1' )
function1( A )
And it tries to call the function function1( A, B)
from the file Root/class2/function1.m
instead of call the function function function1( A )
from the file Root/class1
, outputting the error:
error: 'B' undefined near line 4 column 27
How to call the function function function1( A )
from the file Root/class1/function1.m
while running a file from the folder Root/class2
overloading the function within the current "context"?
I want to call a function from another folder, but over there, it has the same name as a function within the current folder.
You're not giving us much information. It all depends why you're doing this, and whether you're the one developing / using this code.
But in general, you should NOT be adding folders containing functions with the same name to the current working path. And you should most definitely NOT use the word "function" as a name for a function, since that will shadow the function
keyword and all hell breaks loose.
Here's a few suggestions on how to do what you're trying to do:
% in file class1.m:
classdef class1
methods(Static)
function myfunction(A)
fprintf('Hello from class1: A is %d\n', A);
end
end
end
% in file class2.m
classdef class2
methods(Static)
function myfunction(A,B);
fprintf('Hello from class2: A is %d and B is %d\n', A, B);
end
end
end
% at the terminal:
>> class1.myfunction(5)
Hello from class1: A is 5
>> class2.myfunction(5, 3)
Hello from class2: A is 5 and B is 3
Root/class1/myfunction.m
into Root/+class1/myfunction.m
. The "plus" makes that folder a "package", which means you can do this (from the Root folder):
class1.myfunction(5);
class2.myfunction(5,3);
cd
to it instead, use your function from that directory, and then cd
back to where you were. E.g, say you have a folder Root/class1
with file myfunction.m
, and folder Root/class2
with files myfunction.m
and myscript.m
. Then in myscript.m
you write:
% go to class1 directory to use the conflicting function
cd '../class1'
myfunction(5)
% come back to class2
cd '../class2'
myfunction(5, 3 )
However, please note that this is the least recommended method! since it could go horribly wrong! (e.g. if one of the functions changes directories or relies on a particular folder structure, etc.)