Functions Inside Class Definition Files - MATLAB & Simulink (original) (raw)

Main Content

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 definesmyUtilityFcn outside the classdef block.

classdef MyClass properties PropName end methods function obj = method1(val) adjustedVal = myUtilityFcn(val) ... end end end % End of classdef

function out = myUtilityFcn(in) ... end

When you call method1 of MyClass, the method first usesmyUtilityFcn 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

classdef

Topics