Main Content

Functions Inside Class Definition Files

Just as you can define local functions in a script file or function file, you can also define local functions inside a classdef file. Define these functions outside of the classdef block, but in the same file as the class definition. You can call these functions from anywhere in the same file, but they are not visible outside of the file in which you define them.

Local functions in classdef files are useful for utility functions that you use only within that file. For example, this code defines myUtilityFcn outside the classdef block.

classdef MyClass
      function obj = method1(val)
         adjustedVal = myUtilityFcn(val)
end % End of classdef

function out = myUtilityFcn(in)

When you call method1 of MyClass, the method first uses myUtilityFcn to perform some preprocessing on the input argument before performing any other actions.

Unlike methods, these functions do not require an instance of the class as an input, but they can take or return arguments that are instances of the class and access the members of those instances, including private members. However, if a function inside a class definition file needs direct access to class members, consider defining the function as a method of the class instead.

See Also

Related Topics