Call MATLAB Function from C# Client
To call a MATLAB® function from a C# application in MATLAB R2022b or later, consider using the MATLAB Engine API for .NET. For more information, see Call MATLAB from .NET. For an example, see Execute MATLAB Functions from .NET.
If you need to maintain existing programs created for MATLAB R2022a or earlier, use this example which shows how to call a
user-defined MATLAB function
myfunc from a C# application using
MATLAB as a COM Automation server. The example uses early-binding to a
specific MATLAB version.
To use this example, you must know how to create and run a COM console application in a development environment such as Microsoft® Visual Studio®.
Create a MATLAB function
myfunc in the folder
function [x,y] = myfunc(a,b,c) x = a + b; y = sprintf('Hello %s',c);
Create the C# console application in your development environment. The reference to the MATLAB Type Library for C# is:
MLApp.MLApp matlab = new MLApp.MLApp();
Here is the complete example:
From your C# client program, add a reference to your project to the MATLAB COM object. This reference binds your program to a specific version of MATLAB. Refer to your vendor documentation for details. For example, in Microsoft Visual Studio, open your project. From the Project menu, select Add Reference. Select the COM tab in the Add Reference dialog box. Select the MATLAB application.
Build and run the application in your development environment.