Integrate External/Custom Code
This example shows how to integrate external or custom code to enhance performance of generated code. Although MATLAB® Coder™ generates optimized code for most applications, you might have custom code optimized for your specific requirements. For example:
You have custom libraries optimized for your target environment.
You have custom libraries for functions not supported by MATLAB Coder.
You have custom libraries that meet standards set by your company.
In such cases, you can integrate your custom code with the code generated by MATLAB Coder.
This example illustrates how to integrate the function
cublasSgemm
from the NVIDIA®
CUDA® Basic Linear Algebra Subroutines (CUBLAS) library in generated code.
This function performs matrix multiplication on a Graphics Processing Unit
(GPU).
Define a class
ExternalLib_API
that derives from the classcoder.ExternalDependency
.ExternalLib_API
defines an interface to theCUBLAS
library through the following methods:getDescriptiveName
: Returns a descriptive name forExternalLib_API
to be used for error messages.isSupportedContext
: Determines if the build context supports theCUBLAS
library.updateBuildInfo
: Adds header file paths and link files to the build information.GPU_MatrixMultiply
: Defines the interface to theCUBLAS
library functioncublasSgemm
.
To perform the matrix multiplication using the interface defined in method
GPU_MatrixMultiply
and the build information inExternalLib_API
, include the following line in your MATLAB code:C= ExternalLib_API.GPU_MatrixMultiply(A,B);
For instance, you can define a MATLAB function
Matrix_Multiply
that solely performs this matrix multiplication.function C = Matrix_Multiply(A, B) %#codegen C= ExternalLib_API.GPU_MatrixMultiply(A,B);
Define a
MEX
configuration object usingcoder.config
. For using theCUBLAS
libraries, set the target language for code generation toC++
.cfg=coder.config('mex'); cfg.TargetLang='C++';
Generate code for
Matrix_Multiply
usingcfg
as the configuration object and two2 X 2
matrices of typesingle
as arguments. SincecublasSgemm
supports matrix multiplication for data typefloat
, the corresponding MATLAB matrices must have typesingle
.codegen -config cfg Matrix_Multiply ... -args {ones(2,'single'),ones(2,'single')}
Test the generated
MEX
functionMatrix_Multiply_mex
using two2 X 2
identity matrices of typesingle
.Matrix_Multiply_mex(eye(2,'single'),eye(2,'single'))
The output is also a
2 X 2
identity matrix.
See Also
coder.ceval
| coder.opaque
| coder.rref
| coder.wref
| assert
| coder.ExternalDependency
| coder.BuildConfig