Create a COM Component with MATLAB Code
R2026bSupported platform: Windows®
This example creates a COM (Component Object Model) component using a MATLAB® function and integrates it into an application. The target system does not require a licensed copy of MATLAB.
After you package and install a COM component, you can access the component in any program that supports COM, such as Microsoft® Visual Basic®, Microsoft Visual C++®, or Visual C#. For information about programming with COM objects using Visual Basic, see articles in the Microsoft Developer Network (MSDN) Library.
Prerequisites
Verify that you have the Windows 10 SDK kit installed. For details, see Windows 10 SDK.
Verify that you have MinGW-w64 installed. To install it from the MathWorks® File Exchange, see MATLAB Support for MinGW-w64 C/C++ Compiler.
To ensure that MATLAB can detect the Windows 10 SDK kit and MinGW-w64, use the following command:
mbuild -setup -client mbuild_com
Verify that you have Microsoft Visual Studio® installed.
End users must have an installation of MATLAB Runtime to run the application. For details, see Download and Install MATLAB Runtime.
For testing purposes, you can use an installation of MATLAB instead of MATLAB Runtime.
Create Function in MATLAB
In MATLAB, examine the MATLAB code that you want to package. For this example, create the
makesquare.m function.
function y = makesquare(x)
y = magic(x);At the MATLAB command prompt, enter makesquare(5).
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9Create COM Component Using compiler.build.COMComponent
Package the function into a COM component using the
compiler.build.comComponent function. Alternatively, if you
want to create a COM component using a graphical approach, see Create COM Component Using COM Component Compiler App.
To build the COM component, use the
compiler.build.comComponentfunction. Use name-value arguments to specify the component name and class name.buildResults = compiler.build.comComponent("makesquare.m",... "ComponentName","MagicSquareComp",... "ClassName","Class1");
You can specify additional options in the
compiler.buildcommand by using name-value arguments. For details, seecompiler.build.comComponent.The
compiler.build.ResultsobjectbuildResultscontains information on the build type, generated files, included support packages, and build options.The build function generates files within a folder named
MagicSquareCompcomComponentin your current working folder. For information on the files generated, see Files Generated After Packaging MATLAB Functions.Note
The generated component does not include MATLAB Runtime or an installer. To create an installer using the
buildResultsobject, seecompiler.package.installer.
Integrate into Visual Basic Application
To integrate your COM component into a Visual Basic application, see Integrate COM Component into Visual Basic Application.
See Also
compiler.build.comComponent | COM
Component Compiler | mcc