Ordinary methods define functions that operate on objects of the class. Therefore, one of the input arguments must be an object or array of objects of the defining class. These methods can compute values based on object data, can overload MATLAB® built-in functions, and can call other methods and functions. Ordinary methods can return modified objects.
This example shows the definition of a method (
classdef ClassName methods (AttributeName = value,...) function methodName(obj,args) % method code ... end ... end % end of method block ... end
Method attributes apply only to that particular methods block,
which is terminated by the
Note: Nonstatic methods must include an explicit object variable as a function argument. The MATLAB language does not support an implicit reference in the method function definition.
addData method adds a value to the
MyData objects. The
has a default value of
classdef MyData properties Data = 0; end methods function obj = addData(obj,val) newData = obj.Data + val; obj.Data = newData; end end end
a = MyData; a = addData(a,75)
a = MyData with properties: Data: 75
Either of the following statements is correct syntax for calling
a method, where
obj is an object of the class defining
You can define methods:
Inside the class definition block
In a separate file in the class folder (that is,
For more information on class folders, see Folders Containing Class Definitions.