How to call a MATLAB Function from C#

Say you have a MATLAB function called “myfunction” as follows

function [x] = myfunc(a,b) 
x = a + b; 
end

Save this function in a file called “myfunction.m” at “c:tempexample”. 

Create a C# Console Application and add a reference to “Matlab Application (version x.x) Type Library” COM object.

Copy and paste the following code to your Main method.

using System; 
using System.Collections.Generic; 
using System.Text; 

namespace ConsoleApplication
{ 
    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:tempexample"); 

            // Define the output 
            object result = null; 

            // Call the MATLAB function myfunc
            matlab.Feval("myfunc", 1, out result, 2, 3 ); 
             
            // Display result 
            object[] res = result as object[]; 
             
            Console.WriteLine(res[0]);
            Console.ReadLine(); 
        } 
    } 
} 

In the code Feval function evaluate your function. I have provide the arguments; function name, number of output parameters, return result, first input parameter, second input parameter for my MATLAB function. You can pass all your parameters here.

Now you should be able to run the program and see “5” printed on the console.

References:

http://www.mathworks.com/help/matlab/matlab_external/call-matlab-function-from-c-client.html

Advertisements

Author: Harshani Nawarathna

Sri Lankan woman in Computing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s