Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

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[]; 
             
            Console.WriteLine(res[0]); 
            Console.WriteLine(res[1]); 
            Console.ReadLine(); 
        } 
    } 
} 

In Microsoft® Visual Studio®, add a reference to your C# project to the MATLAB COM object. From the Project menu, select Add Reference.

Select the COM tab in the Add Reference dialog box.

Select the MATLAB application.

Was this topic helpful?