MATLAB の値クラスのコード生成
この例では、MATLAB® の値クラスのコードを生成する方法について説明し、コード生成レポートで生成されたコードを示します。
書き込み可能なフォルダーに、MATLAB 値クラス
Shape
を作成します。Shape.m
としてコードを保存します。classdef Shape % SHAPE Create a shape at coordinates % centerX and centerY properties centerX; centerY; end properties (Dependent = true) area; end methods function out = get.area(obj) out = obj.getarea(); end function obj = Shape(centerX,centerY) obj.centerX = centerX; obj.centerY = centerY; end end methods(Abstract = true) getarea(obj); end methods(Static) function d = distanceBetweenShapes(shape1,shape2) xDist = abs(shape1.centerX - shape2.centerX); yDist = abs(shape1.centerY - shape2.centerY); d = sqrt(xDist^2 + yDist^2); end end end
同じフォルダーに、
Shape
のサブクラスとなるSquare
クラスを作成します。Square.m
としてコードを保存します。classdef Square < Shape % Create a Square at coordinates center X and center Y % with sides of length of side properties side; end methods function obj = Square(side,centerX,centerY) obj@Shape(centerX,centerY); obj.side = side; end function Area = getarea(obj) Area = obj.side^2; end end end
同じフォルダーに、
Shape
のサブクラスとなるRhombus
クラスを作成します。Rhombus.m
としてコードを保存します。classdef Rhombus < Shape properties diag1; diag2; end methods function obj = Rhombus(diag1,diag2,centerX,centerY) obj@Shape(centerX,centerY); obj.diag1 = diag1; obj.diag2 = diag2; end function Area = getarea(obj) Area = 0.5*obj.diag1*obj.diag2; end end end
このクラスを使用する関数を書きます。
function [TotalArea, Distance] = use_shape %#codegen s = Square(2,1,2); r = Rhombus(3,4,7,10); TotalArea = s.area + r.area; Distance = Shape.distanceBetweenShapes(s,r);
use_shape
のスタティック ライブラリを生成し、コード生成レポートを生成します。codegen -config:lib -report use_shape
codegen
によって C のスタティック ライブラリが既定の名前use_shape
で生成され、既定のフォルダーcodegen/lib/use_shape
にサポート ファイルが生成されます。[レポートの表示] リンクをクリックします。
Rhombus
クラス定義を確認するには、[MATLAB ソース] ペインの [Rhombus.m
] の下にある [Rhombus
] をクリックします。Rhombus
クラス コンストラクターが強調表示されます。[変数] タブをクリックします。変数
obj
はRhombus
クラスのオブジェクトであることがわかります。このプロパティを表示するには、obj
を展開します。[MATLAB ソース] ペインでは、[呼び出しツリー] をクリックします。
[呼び出しツリー] ビューには、
use_shape
がRhombus
コンストラクターを呼び出し、Rhombus
コンストラクターがShape
コンストラクターを呼び出していることが表示されます。コード ペインの
Rhombus
クラス コンストラクター内でポインターを次の行に移動します。obj@Shape(centerX,centerY)
Rhombus
クラスのコンストラクターが、基底Shape
クラスのShape
メソッドを呼び出します。Shape
クラス定義を表示するには、obj@Shape
でShape
をダブルクリックします。