#callmatlabfromcsharp
Explore tagged Tumblr posts
Text
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:\temp\example”.
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:\temp\example"); // 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
0 notes