- assignin: https://in.mathworks.com/help/matlab/ref/assignin.html
- function handles: https://in.mathworks.com/help/matlab/ref/function_handle.html
Automate import statements in base workspace
5 views (last 30 days)
Show older comments
There is a large project that I'm organizing into packages. Many of the packages have classes that are useful to the user. I would like to be able to make a shortcut function/script that will import the useful classes into the base workspace to make it easy for the user to access them. For example, consider the user wanting to use classA, classB, and classC which are organized somewhere in the package hierarchy, e.g., pkg1.sub1.classA, pkg1.sub2.classB, pkg1.sub3.classC. I would like to create a script (called imports.m for instance) that runs the following in the base workspace:
import pkg1.sub1.classA
import pkg1.sub2.classB
import pkg1.sub3.classC
This way the user can directly access classA, classB, and class C without having to traverse and/or know the package hierarchy. I have tried making a script and function with the following:
evalin("base", "import pkg1.sub1.classA")
evalin("base", "import pkg1.sub2.classB")
evalin("base", "import pkg1.sub3.classC")
However, this does not affect the imports in the base workspace as I would expect. Is there any way to do this?
0 Comments
Answers (1)
Poorna
on 13 Sep 2023
Hi Zac,
I understand that you want to write a script that will automatically import classes, so that the user can use these useful classes without having to know the package hierarchy.
You can achieve the desired behaviour using “assignin” function to assign a function handler of the class’s constructor in the base workspace.
Inside the script, first import the class using the “import” statement, then use the “assignin” function to assign the function handle of the class constructor to a variable in the base class as shown below:.
function imports
import pkg1.sub1.classA
%assign a function handle of classA in the base workspace.
assignin('base', 'classA', @classA);
end
After, calling the imports function, you can create an object of “classA” as shown below:
obj = classA();
Hope this helps!
Kindly refer to the following links to know more about the functions used above:
0 Comments
See Also
Categories
Find more on Whos 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!