最終更新:2021-05-10 (月) 10:05:50 (1079d)  

MALTAB/クラス
Top / MALTAB / クラス

https://jp.mathworks.com/help/matlab/object-oriented-programming.html

https://jp.mathworks.com/help/matlab/sample-classes.html

他の言語との比較

機能

  • 関数と演算子のオーバーロード
  • プロパティとメソッドへの制御アクセス
  • 参照と値のセマンティクス
  • イベントとリスナー

文法

  • classdef BasicClass
       properties
          Value {mustBeNumeric}
       end
       methods
          function r = roundOff(obj)
             r = round([obj.Value],2);
          end
          function r = multiplyBy(obj,n)
             r = [obj.Value] * n;
          end
       end
    end
  • a = BasicClass

完全なクラス

  • classdef (Sealed) MyClass < handle
       properties (SetAccess = private)
          Prop1 = datenum(date)
       end
       properties
          Prop2
       end
       methods
          function obj = MyClass(x)
             obj.Prop2 = x;
          end
       end
       methods (Access = {?MyOtherClass})
          function d = myMethod(obj)
             d = obj.Prop1 + x;
          end
       end
       events (ListenAccess = protected)
          StateChanged
       end
    end

properties

  • 最初、プロパティ値は空です。
  • プロパティ = 初期値
    • {mustBeNumeric?}
  • properties
  • properties(Access = private)
  • properties(Access = private, Nontunable)

methods

  • multiplyBy メソッドの呼び出しのように、複数の引数を取るメソッドには、オブジェクトを 1 番目の引数として渡します
    multiplyBy(a,3)
  • また、ドット表記を使用してメソッドを呼び出すこともできます。
    a.multiplyBy(3)
  • ベクトル化
    [obj.Value] + 2

オーバーロード

  • 既存の MATLAB 関数と同じ名前でメソッドを定義することにより、加算などの既存の機能を実装できます
  • plus

events

enumeration