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 class coder.ExternalDependency
. ExternalLib_API
defines
an interface to the CUBLAS
library through the
following methods:
getDescriptiveName
: Returns a descriptive
name for ExternalLib_API
to be used for error messages.
isSupportedContext
: Determines
if the build context supports the CUBLAS
library.
updateBuildInfo
: Adds header file
paths and link files to the build information.
GPU_MatrixMultiply
: Defines the
interface to the CUBLAS
library function cublasSgemm
.
To perform the matrix multiplication using the interface
defined in method GPU_MatrixMultiply
and the build
information in ExternalLib_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
using coder.config
. For using the CUBLAS
libraries,
set the target language for code generation to C++
.
cfg=coder.config('mex'); cfg.TargetLang='C++';
Generate code for Matrix_Multiply
using cfg
as
the configuration object and two 2 X 2
matrices
of type single
as arguments. Since cublasSgemm
supports
matrix multiplication for data type float
, the
corresponding MATLAB matrices must have type single
.
codegen -config cfg Matrix_Multiply ... -args {ones(2,'single'),ones(2,'single')}
Test the generated MEX
function Matrix_Multiply_mex
using
two 2 X 2
identity matrices of type single
.
Matrix_Multiply_mex(eye(2,'single'),eye(2,'single'))
The output is also a 2 X 2
identity matrix.
assert
| coder.BuildConfig
| coder.ceval
| coder.ExternalDependency
| coder.opaque
| coder.rref
| coder.wref