Main Content

CallMATLABFunction from C# Client

This example shows how to call a user-defined MATLAB®functionmyfuncfrom a C# application using MATLAB as a COM Automation server. For more information about COM, seeWrite COM Applications to Work with MATLAB.

The example uses early-binding to a specific MATLAB version.

Note

To use this example, you must know how to create and run a COM console application in a development environment such asMicrosoft®Visual Studio®.

Create a MATLAB functionmyfuncin the folderc:\temp\example.

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:

using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { // Create the MATLAB instance MLApp.MLApp matlab = new MLApp.MLApp(); // Change to the directory where the function is located matlab.Execute(@"cd c:\temp\example"); // Define the output object result = null; // Call the MATLAB function myfunc matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world"); // Display result object[] res = result as object[]; Console.WriteLine(res[0]); Console.WriteLine(res[1]); // Get user input to terminate program Console.ReadLine(); } } }

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, inMicrosoft Visual Studio, open your project. From theProjectmenu, selectAdd Reference. Select theCOMtab in the Add Reference dialog box. Select the MATLAB application.

Build and run the application in your development environment.

See Also

|

Related Topics