Main Content

Ordinary Methods

Ordinary Methods Operate on Objects

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.

Methods Inside classdef Block

This example shows the definition of a method (methodName) within the classdef and methods blocks:

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 end statement.

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.

Example of a Method

The addData method adds a value to the Data property of MyData objects. The mustBeNumeric function restricts the value of the Data property to numeric values. The property has a default value of 0.

The addData method returns the modified object, which you can reassign to the same variable.

classdef MyData
   properties
      Data {mustBeNumeric} = 0
   end
   methods
      function obj = addData(obj,val)
         if isnumeric(val)
            newData = obj.Data + val;
            obj.Data = newData;
         end
      end
   end
end
a = MyData;
a = addData(a,75)
a = 

  MyData with properties:

    Data: 75

Method Files

You can define methods:

  • Inside the class definition block

  • In a separate file in the class folder (that is, @ClassName folder)

For more information on class folders, see Folders Containing Class Definitions.

Related Topics