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_APIthat derives from the classcoder.ExternalDependency.ExternalLib_APIdefines an interface to theCUBLASlibrary through the following methods:getDescriptiveName: Returns a descriptive name forExternalLib_APIto be used for error messages.isSupportedContext: Determines if the build context supports theCUBLASlibrary.updateBuildInfo: Adds header file paths and link files to the build information.GPU_MatrixMultiply: Defines the interface to theCUBLASlibrary functioncublasSgemm.
To perform the matrix multiplication using the interface defined in method
GPU_MatrixMultiplyand 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_Multiplythat solely performs this matrix multiplication.function C = Matrix_Multiply(A, B) %#codegen C= ExternalLib_API.GPU_MatrixMultiply(A,B);
Define a
MEXconfiguration object usingcoder.config. For using theCUBLASlibraries, set the target language for code generation toC++.cfg=coder.config('mex'); cfg.TargetLang='C++';
Generate code for
Matrix_Multiplyusingcfgas the configuration object and two2 X 2matrices of typesingleas arguments. SincecublasSgemmsupports 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
MEXfunctionMatrix_Multiply_mexusing two2 X 2identity matrices of typesingle.Matrix_Multiply_mex(eye(2,'single'),eye(2,'single'))
The output is also a
2 X 2identity matrix.
See Also
coder.ceval | coder.opaque | coder.rref | coder.wref | assert | coder.ExternalDependency | coder.BuildConfig
