LoginSignup
7
6

More than 5 years have passed since last update.

matlabでのクラス生成(handleクラスと値クラスの比較)

Posted at

matlabでクラスを設計する際,handleクラスを継承するかどうかで振る舞いが全く異なるものになる.
今回はそれを簡単に考察してみます.

まずはhandle継承版

testclass.m

classdef testclass < handle
    properties
        input
    end
    methods
        % constructor
        function obj= testclass(varargin)
            if(nargin==1)
                obj.input=varargin{1};
            else
                obj.input=0;
            end
        end
        % normal method
        function [] = func(varargin)
            obj=varargin{1};
            obj.input=obj.input+1;
        end
    end
    methods(Static)
        % static method
        function [] = func_stat(varargin)
            obj=varargin{1};
            obj.input=obj.input+1;
        end
    end
 end

実行してみます.

>> test=testclass(1)

test = 

  testclass handle

  Properties:
    input: 1

  Methods, Events, Superclasses
>> test.func
>> test

test = 

  testclass handle

  Properties:
    input: 2

  Methods, Events, Superclasses

インスタンス中のプロパティがちゃんとインクリメントされました.

静的メソッドの場合,引数にて陽にインスタンスを指定する必要があります.

>> test.func_stat
Index exceeds matrix dimensions.

Error in testclass.func_stat (line 23)
            obj=varargin{1};

>> test.func_stat(test)
>> test

test = 

  testclass handle

  Properties:
    input: 3

  Methods, Events, Superclasses

インスタンス中のプロパティがちゃんとインクリメントされました.

余談ですが,静的メソッドはインスタンス無しでも実行可能です.

>> testclass.func_stat
Index exceeds matrix dimensions.

Error in testclass.func_stat (line 23)
            obj=varargin{1};

>> testclass.func_stat(test)
>> test

test = 

  testclass handle

  Properties:
    input: 4

  Methods, Events, Superclasses

handleクラスを継承しない場合

testclass.m
classdef testclass %< handle ハンドルをコメントアウトしてみます.
   ...  (省略)
end
>> test=testclass(1)

test = 

  testclass handle

  Properties:
    input: 1

  Methods, Events, Superclasses
>> test=testclass(1)

test = 

  testclass

  Properties:
    input: 1

  Methods

>> test.func
>> test

test = 

  testclass

  Properties:
    input: 1

  Methods

インクリメントされません.
この場合,メソッドの出力に入力のインスタンスを指定する必要があります.

        % normal method 2
        function [obj] = func2(varargin)
            obj=varargin{1};
            obj.input=obj.input+1;
        end
>> test=testclass(1)

test = 

  testclass

  Properties:
    input: 1

  Methods

>> test.func2

ans = 

  testclass

  Properties:
    input: 2

  Methods

>> test=test.func2

test = 

  testclass

  Properties:
    input: 2

  Methods

handleクラスを継承した方がスマートに書けますね.

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6