Ordinary Methods

Defining Methods

You can specify methods:

  • Inside of a class definition block

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

Methods Inside classdef Block

This example shows the definition of a method (the compute function in this example) within the classdef and methods blocks:

classdef ClassName
   methods (AttributeName = value,...)
      function x = compute(obj,inc)
         x = obj.y + inc;
      end % compute method
   end % methods block
end % classedf

    Note:   Nonstatic methods must include an explicit object variable in the function definition. The MATLAB® language does not support an implicit reference in the method function definition.

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


Method attributes apply only to that particular methods block, which is terminated by the end statement.

Multi-File Classes

You can define class methods in separate files within the class folder. In this case, create a function in a separate file having the same name as the function (i.e., functionname.m). If you want to specify attribute values for that method, you must declare the method signature within a methods block in the classdef block . For example:

classdef myClass
   methods (AttributeName = value,...)
      tdata = testdata(obj,arg1,arg2)
   end % methods
end % classdef

Do not use methods blocks in the separate files. Define the method as a function. Using the example above, the file testdata.m, must contain the definition of the testdata function. Note that the signatures must match.

function tdata = testdata(myClass_object,argument2,argument3)

The following limitations apply to methods defined in separate files:

  • If you want to specify attributes for a method defined in a separate file, you must declare this method in a methods block (specifying attribute values) within the classdef block.

  • The syntax declared in the methods block (if used) must match the method's function line.

  • The separate file must be in the class folder.

  • The constructor method must be defined within the classdef block and, therefore, cannot be in a separate file.

  • Set and get property access methods must be defined within the classdef block and, therefore, cannot be in separate files.

More About

Was this topic helpful?