Import Namespace Members into Functions - MATLAB & Simulink (original) (raw)

Main Content

When referencing namespace members inside a function, you can simplify access to namespace members by importing them into the function. Once you have imported the code, you do not need to use the namespace name.

Note

The namespace names and members used here are for example purposes only. They are not part of the MATLABĀ® installation. To experiment with the functionality, define these folders and code on your own path.

Import Classes, Namespace Functions, and Static Methods

For example, use the import command to importMyClass from the namespace mynamesp. You can then reference MyClass inside the function without the namespace name.

function exampleFunction import mynamesp.MyClass obj = MyClass(arg,...); % call MyClass constructor obj.Prop = MyClass.staticMethod(arg,...); % call MyClass static method end

The same process works for namespace functions and static methods, as shown in these examples. Importing the code into the function enables you to call the code without the namespace.

function myFuncA import mynamesp.myFunction myFunction(arg,...); % call imported namespace function end

function myFuncB import mynamesp.MyClass.myStaticMethod myStaticMethod(arg,...); % call static method end

You can import all code in a namespace using the syntaxmynamesp.*. However, you should avoid doing so because of potential naming conflicts. See Importing Namespace Members with the Same Name for more information.

Importing Namespace Members with the Same Name

Use caution when importing namespace members to avoid name conflicts. For example, this folder hierarchy contains a namespace function and a class method with the same name, timedata.

+mynamesp/timedata.m % namespace function +mynamesp/@MyClass/MyClass.m % class definition file +mynamesp/@MyClass/timedata.m % class method

Import the namespace and attempt to call timedata on an instance of MyClass.

import mynamesp.* myobj = MyClass; timedata(myobj)

Calling timedata using the function syntax instead of the dot syntax calls the namespace function because MATLAB finds the imported function first.

Clear an Import List

You cannot clear the import list from a function workspace. However, you can clear the base workspace using clear import.

See Also

import

Topics