Call MATLAB Function from C# Client

This example shows how to call a user-defined MATLAB® function myfunc from a C# application.

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# application.

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[]; 

From your C# client program, add a reference to your project to the MATLAB COM object. 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. Refer to your vendor documentation for details.

See Also


Related Topics