| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
See Scoping Classes with Packages for information about packages.
You can import classes into a function to simplify access to class members. For example, suppose there is a package that contains a number of classes, but you need to use only one of these classes in your function, or perhaps even just a static method from that class. You can use the import command as follows:
function myFunc import pkg.cls1 obj = cls1(arg,...); % call cls1 constructor obj.Prop = cls1.StaticMethod(arg,...); % call cls1 static method end
Note that you do not need to reference the package name (pkg) once you have imported the class (cls1). You can also import all classes in a package using the syntax pkg.*, where * indicates all classes in the package. For example,
function myFunc import pkg.* obj1 = cls1(arg,...); % call pkg.cls1 constructor obj2 = cls2(arg,...); % call pkg.cls2 constructor a = pkgFunction(); % call package function named pkgFunction end
You can use import with package functions:
function myFunc import pkg.pkfcn pkfcn(arg,...); % call imported package function end
Suppose you have the following directory organization:
+pkg/timedata.m % package function +pkg/@myclass/myclass.m % class definition file +pkg/@myclass/timedata.m % class method
Now import the package and call timedata on an instance of myclass:
import pkg.* myobj = pkg.myclass; timedata(myobj)
A call to timedata finds the package function, not the class method because MATLAB applies the import and finds pkg.timedata first. You should not use a package in cases where you have name conflicts and plan to import the package.
You can not clear the import list from a function workspace. To clear the base workspace only, use:
clear import
![]() | Scoping Classes with Packages | Referring to Constant Values | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |