为 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
在同一文件夹中,创建一个类
Square
,它是Shape
的子类。将代码另存为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
在同一文件夹中,创建一个类
Rhombus
,它是Shape
的子类。将代码另存为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
使用默认名称use_shape
和默认文件夹codegen/lib/use_shape
中的支持文件生成一个 C 静态库。点击查看报告链接。
要查看
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
。