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; 

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

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.



Author: Harshani Nawarathna

Sri Lankan woman in Computing

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s