Call MATLAB Function from C# Client

This example shows how to call a user-defined MATLAB® function myfunc from a C# application using MATLAB as a COM Automation server. For more information about COM, see Calling MATLAB as COM Automation Server.

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 as Microsoft® Visual Studio®.

Create a MATLAB function myfunc in the folder c:\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.

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, 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.

See Also

|

Related Topics