Generate Code for MATLAB Value Classes - MATLAB & Simulink (original) (raw)
This example shows how to generate code for a MATLABĀ® value class and then view the generated code in the code generation report.
- In a writable folder, create a MATLAB value class,
Shape
. Save the code asShape.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 - In the same folder, create a class,
Square
, that is a subclass ofShape
. Save the code asSquare.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 - In the same folder, create a class,
Rhombus
, that is a subclass ofShape
. Save the code asRhombus.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.5obj.diag1obj.diag2;
end
end
end - Write a function that uses this class.
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); - Generate a static library for
use_shape
and generate a code generation report.
codegen -config:lib -report use_shapecodegen
generates a C static library with the default name,use_shape
, and supporting files in the default folder,codegen/lib/use_shape
. - Click the View report link.
- To see the
Rhombus
class definition, on the MATLAB Source pane, underRhombus.m
, clickRhombus
. TheRhombus
class constructor is highlighted. - Click the Variables tab. You see that the variable
obj
is an object of theRhombus
class. To see its properties, expandobj
. - In the MATLAB Source pane, click Call Tree.
The Call Tree view shows thatuse_shape
calls theRhombus
constructor and that theRhombus
constructor calls theShape
constructor. - In the code pane, in the
Rhombus
class constructor, move your pointer to this line:
obj@Shape(centerX,centerY)
The Rhombus
class constructor calls the Shape
method of the base Shape
class. To view the Shape
class definition, in obj@Shape
, double-click Shape
.