I am trying to write a generic function to preform a calculation using the appropriate namespace/package as specified by the input parameters. Obviously I could do this using eval, however this is quite clumsy and I'm hoping there is a better way. I thought import would work, as the documentation says imports within a function effect only the workspace/import list of that function, but alas this is not the case.
I have included example code below, as well as a zip file with the folder structure intact.
Example:
I have two packages pkg1 and pkg2 each of which implements a function, commonFunction
function commonFunction
disp('Using pkg1')
end
function commonFunction
disp('Using pkg2')
end
function testPackages(packageNameString)
import(packageNameString)
commonFunction
end
clear all
id1 = 'pkg1.*';
id2 = 'pkg2.*';
testPackages(id1)
testPackages(id2)
clear import
testPackages(id2)
testPackages(id1)
clear all
id1 = 'pkg1.*';
id2 = 'pkg2.*';
testPackages(id2)
testPackages(id1)
clear all
id1 = 'pkg1.commonFunction';
id2 = 'pkg2.commonFunction';
testPackages(id1)
testPackages(id2)
clear import
testPackages(id2)
testPackages(id1)
clear all
id1 = 'pkg1.commonFunction';
id2 = 'pkg2.commonFunction';
testPackages(id2)
testPackages(id1)