Introduction
As an example we’ve got a flowery numerical routine that we have been engaged on in MATLAB that we wish to make the most of in an exterior C++ software. On this submit, we’ll present how we will generate a dynamic library from MATLAB code which we will name from a C++ program. This can permit us to harness a few of the energy of MATLAB in an exterior program.
The MATLAB Code
The minimal of might be discovered utilizing the standard strategy of taking the by-product of it with respect to m and b and setting these to zero. Doing so provides us the next system of two equations:
and
Right here we’ve got used the truth that the by-product operator and sum commute. After dividing either side of each equations by -2, we will rearrange this method right into a matrix equation
This technique might be written in compact notation as
To unravel for $ p=[m,b]^T $ , we will multiply either side by the inverse of H
or just
The MATLAB code to resolve for m and b appears like this:
perform [m, b] = lineFitter(x,y)
% Be sure that x and y have the identical variety of parts
assert(numel(x)==numel(y));
% Type the left hand matrix
H = [x(:)’*x(:) sum(x(:),1);
sum(x(:),1) numel(x)];
% Type the residual
f = [x(:)’*y(:)
sum(y(:),1)];
% Clear up the system
p = Hf;
% Assign the slopes
m = p(1);
b = p(2);
finish
Testing the Becoming Routine In MATLAB
To verify our code, let’s load some information, match the road and plot the whole lot.
d = readmatrix(“myData.csv”);
% Create the road from the fitted parameters
plot(xgrid, ygrid, “LineWidth”, 2);
Generate Code for the Becoming Routine
% Arrange coder object for a dynamic library
cfg = coder.config(‘dll’);
% Create pattern variables for the inputs. We wish to make these inputs
% dynamically sized as a result of we might have arbitrarily sized information information.
xarg = coder.typeof(1.0, [10000, 1], [1, 0]);
yarg = coder.typeof(1.0, [10000, 1], [1, 0]);
% Generate the code and a report
codegen -config cfg lineFitter.m -args {xarg,yarg} -nargout 2 -report
The related code that we’ll want later is the interface to lineFitter. The important thing code is in lineFitter.h:
/* Perform Declarations */
extern void lineFitter(const emxArray_real_T *x, const emxArray_real_T *y,
double *m, double *b);
The inputs are fixed array pointers and the outputs are tips to doubles. This can information our client-side implementation as we’ll present under.
Packaging the Code
codebuild(‘./codegen/dll/lineFitter’, ‘BuildMethod’, ‘CMake’, ‘BuildVariant’, ‘SHARED_LIBRARY’);
packNGo(‘./codegen/dll/lineFitter’, ‘PackType’, ‘hierarchical’, ‘fileName’, ‘lineFitter’);
This generates an archive file lineFitter.zip, which we will copy to our consumer codebase.
Create the Dynamic Library
Now that we’ve got our code, we’re able to construct it and create a routine to hyperlink to it on the consumer machine. After that we will add the code we have to name our line becoming routine within the consumer code. As an example we put our newly generated lineFitter.zip right here and unzip the whole lot. Unzipping lineFitter.zip will produce two information, mlrFiles.zip and sDirFiles.zip. Unzipping these will create two directories, R2022b and codegen.
C:worklineFitExample> dir /w
[codegen] lineFitter.zip mlrFiles.zip [R2022b] sDirFiles.zip
C:worklineFitExample> mkdir build_lib
C:workLineFitExample> cmake -G “NMake Makefiles” -B ./build_lib -DCMAKE_BUILD_TYPE=Launch -DMATLAB_ROOT=./R2022b -S./codegen/dll/lineFitter
— The C compiler identification is MSVC 19.29.30137.0
<snip>
— Construct information have been written to: C:/work/LineFitExample/build_lib
C:workLineFitExample> cmake –build build_lib
[8/8] Linking CXX shared library codegendlllineFitterlineFitter_win64.dll
### Created library: C:/work/LineFitExample/build_lib/codegen/dll/lineFitter/lineFitter_win64.dll
Utilizing the Dynamic Library
Now that we’ve got generated our dynamic library lineFitter_win64.dll, it is time to create the appliance code that can use the lineFitter routine. Our consumer software reads within the csv file and locations the columns into two lists:
To make this code interface with our newly created dynamic library we have to allocate our arrays. These arrays are of kind emx_Array_real_T as proven above. We’ll write a perform to do the allocation, however first we’ll embrace two header information that we’ll want:
#embrace “lineFitter.h”
#embrace “lineFitter_emxAPI.h”
Now we’re prepared to write down our array allocation perform, which we’ll place above the primary routine. This perform takes an inventory of doubles and copies it into an emxArray_real_T that has been allotted to the correct measurement. An instance of this code might be discovered within the listing .codegendlllineFitterexamplesmain.c.
Lastly, we’ll add the calls to allocate our vectors and remedy the system under the studying code in the primary routine however earlier than the ultimate return assertion:
Our CMakeLists.txt file for our consumer appears like this:
The process is much like compiling the library above, which is a part of the attraction of CMake. The instructions are:
C:workLineFitExample> mkdir construct
C:workLineFitExample> cmake -G “NMake Makefiles” -B construct -S . -DCMAKE_BUILD_TYPE=Launch
— The C compiler identification is MSVC 19.29.30137.0
<snip>
— Construct information have been written to: C:/work/LineFitExample/construct
C:workLineFitExample> cmake –build construct
[2/2] Linking CXX executable myFit.exe
Now we’ve got our executable, myFit.exe within the construct listing. The ultimate steps to check our code are:
C:workLineFitExample> set PATH=C:workLineFitExamplebuild_libcodegendlllineFitter;%PATH%
C:workLineFitExample> .buildmyFit.exe myData.csv
m,b = 4.04926, -0.0246821
As we will see, the slope and intercept are the identical as what we bought in MATLAB.
Notes
[2] On this instance, we use Visible Studio instruments to compile the code. To set this up for the command line, I ran the script:
C:Program Information (x86)Microsoft Visible Studio2019ProfessionalVCAuxiliaryBuildvcvars64.bat
Now it is your flip
We hope you loved this instance. Quickly we’ll observe up with a extra complicated instance constructing on this basis. If there are different Coder associated subjects you want to see coated on the weblog, tell us within the remark under.