Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

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.

Sample Method

The addData method adds a value to the Data property of MyData objects. The Data property has a default value of 0.

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

Calling Methods

Either of the following statements is correct syntax for calling a method, where obj is an object of the class defining the methodName method:

obj.methodName(arg)
methodName(obj,arg)

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.

More About

Was this topic helpful?