Two ways of object-oriented programming in MATLAB _matlab

Source: Internet
Author: User
Tags assert define get types of functions

MATLAB Support object-oriented Programming, there are two main ways, one is the use of class commands, one is the use of classdef keyword. Octave (a source of scientific computing program, can be considered as a substitute for MATLAB) currently only support the first way, ClassDef temporarily do not support. Here's a brief introduction to both of these programming methods. 1. Create class using Class command

Create a @class form of a folder in which class represents the name of the class to implement. Suppose you need to create a class named point, you can create a folder named @point:

mkdir @point

After that, the function defined under the folder @point is treated as a member function of the point class. Mainly include: POINT.M
The constructor function. This is a function with the same name as the class names. Get.m
The property used to get the class point. Set.m
The property that is used to set the class point. Display.m
Used to control the display string for a class. disp.m
With DISPLAY.M, but more advanced than display, in DISP.M will invoke DISPLAY.M. Thus the DISPLAY.M can achieve finer control over the display. Move.m
Can be any user-defined function.

Of the several types of functions listed above, only constructors are required. However, because general object-oriented programming involves access (read and set) to properties, GET.M and SET.M are also implemented in most cases. User-defined functions can or may not be based on different scenarios, and can have multiple user-defined member functions.

Here's a sample code:

% point.m
% constructor function
obj = point (x, y)
persistent id_
if (IsEmpty (id_)); id_ = 0; end

d.id = id_;
d.x = x;
D.y = y;
obj = Class (d, ' point ');

Id_ = id_ + 1;
End
The% get.m
% property gets functions function
val = get (obj, name)
switch name case
    ' x '
        val = obj.x;
    Case ' Y '
        val = obj.y;
    Case ' id '
        val = obj.id;
    otherwise
        error ([' Invalid property: ' name]);
End End
% set.m
% property setting functions function
obj = set (obj, varargin)
n = Numel (varargin);
ASSERT (REM (n, 2) = = 0)

i = 1;
While I < n
    name = varargin{i};
    Val  = varargin{i+1};
    Switch name Case
        ' x '
            obj.x = val;
        Case ' y '
            obj.y = val;
        Case ' ID '
            error (' Set private field ' ID ' isn't allowed ');
        otherwise
            error ([' Invalid property: ' name]);
    End
    i = i + 2;
End End
% DISPLAY.M
% display functions function
display (obj)
fprintf (1, ' point class (id =%d): \ n ', obj.id);
fprintf (1, ' x =%d\n ', obj.x);
fprintf (1, ' y =%d\n ', obj.y);
End
% MOVE.M
% user Custom function
obj = Move (obj, varargin)
assert (Numel (varargin) >= 1);

if (Isstruct (Varargin{1}))
    % move (obj, s)
    s = varargin{1};
    ASSERT (All (Isfield (s, {' x ', ' Y '}));
    obj.x = s.x;
    OBJ.Y = S.y;
else
    % Move (obj, x, y)
    assert (Numel (varargin) >= 2);

    x = varargin{1};
    y = varargin{2};

    obj.x = x;
    Obj.y = y;    
End End

The above code has a certain representativeness. The point function creates a point class using the Class command. It contains two public properties X and Y, as well as a read-only property ID (as can be seen from GET.M and SET.M: The value of the ID can be obtained in GET.M, and the value of the ID cannot be set in SET.M). In addition, we have defined a user-defined method move.

Here are two points: you can access only the properties of class in a member function, which is why you define get and set. Accessing the properties of a class via Point.x or POINT.Y can be an error. Class-generated classes can call their member functions only by function, not by using the. operator to invoke a member function. For example, call the Move function:

Move (Point, 2, 3)

and

Point.move (2, 3)

is illegal. 2. Create a class using the CLASSDEF keyword

ClassDef is the key word for creating classes in MATLAB. Its basic structure is

ClassDef ClassName
   Properties
      propname
   End
   methods
      methodname
   end
   Events
      EventName
   End

Where properties are used to define the properties of a class, methods defines the member functions of the class, and events blocks define the event for the class.
ClassDef supports class inheritance, described by the < operator, separated by & between multiple parent classes. Its basic syntax is:

ClassDef classname [< [Superclass1] & [Superclass2]]
...
End

In the MATLAB oop, the handle class is the base class for all classes.

In addition, methods and properties statement blocks can also take advantage of more descriptors to control their access levels, enabling classes to support properties such as public properties, private properties, public methods, private methods, and static methods. For more details on ClassDef, please refer to the MATLAB documentation or online data.

Here is an example of using ClassDef to implement the Point class in section 1th:

ClassDef Point properties X Y End properties (setaccess = private) ID End me thods function self = point (x, y) persistent id_ if (IsEmpty (id_)); id_ = 0;
            End self.id = id_;
            self.x = x;

            Self.y = y;
        Id_ = id_ + 1;
            End Function display (self) fprintf (1, ' point class:\n ');
            fprintf (1, ' x =%d\n ', self.x);
        fprintf (1, ' y =%d\n ', self.y);

            End Function Move (self, varargin) assert (Numel (varargin) >= 1);
                if (Isstruct (Varargin{1}))% move (obj, s) s = varargin{1};
                ASSERT (All (Isfield (s, {' x ', ' Y '}));
                self.x = s.x;
            SELF.Y = S.y;

                Else% Move (obj, x, y) assert (Numel (varargin) >= 2);
                x = Varargin{1};

      y = varargin{2};          self.x = x;
            Self.y = y; End End End

In the code above, x and Y are the public properties of the point class, and the ID is a private property. ClassDef created class support. operator. Can be passed directly through. Access the properties of the class and the member functions of the calling class. Therefore, you do not need to write a Get function and set function, directly through the point.x to obtain the properties of the class, through the Point.y=1 can be completed on the property settings. This is a slightly easier way to use.

At present Matlab to the ClassDef way support is not very perfect, some application scenario uses MATLAB object-oriented programming in the performance aspect may have some loss; however, object-oriented programming makes the code structure clearer and the internal logic of the program easier to understand. Therefore, it is necessary to make a reasonable choice according to the actual application scenario (reference MATLAB Object-oriented programming is worth using extensively. )。 Since octave currently does not support the CLASSDEF keyword, this approach is not recommended to ensure code portability.

Finally, test code that tests two ways of programming is posted:

 clear all; CLC;

% Test case 1:class Clear all;

% Test Constructor point = Point (1, 2); % Test Getter x = Get (point, ' x ') y = Get (point, ' y ') id = "Get" (Point, ' id ')% of Get (point, ' xx ')% of this should issue 
An error% test setters% Set (point, ' x ')% this should issue a error set (point, ' X ', 2) Set (Point, ' X ', 2, ' Y ', 3) Set (point, ' Y ', 4, ' X ', 5)% set (point, ' id ', 1)% This should issue a error% test display point display (point) disp

(point)% of test user-defined function Move (point, 4, 5) display (point)% of test case 2:classdef clear all;

% Test Constructor point = Point.point (1, 2);
% Test getter x = point.x y = point.y id = point.id% point.xx% This should issue an error% test setter Point.x = 2 Point.y = 3% point.id = 1% This should issue the error% test Display point display (point) Disp p oint)% test user-defined function Point.move (4, 5) display (point) 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.