Call MATLAB Function From C#

13
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(); } }

description

matlab

Transcript of Call MATLAB Function From C#

Call MATLAB Function from C# ClientThis 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.usin !ystem; usin !ystem"#ollections"$eneric; usin !ystem"%ext; namespace #onsole&pplication' ( class )roram ( static *oi+ ,ain(strin[] ars) ( -- #reate t.e ,&%/&0 instance ,/&pp",/&pp matlab = ne1 ,/&pp",/&pp(); -- #.ane to t.e +irectory 1.ere t.e function is locate+ matlab"2xecute(34c+ c:\temp\example4); -- 5e6ne t.e output ob7ect result = null; -- #all t.e ,&%/&0 function myfuncmatlab"8e*al(4myfunc4, ', out result, 9":;, ;'"'eference] option" Kn ne1 1in+o1 clicJ #D, tab" Kn searc. text box 1rite ',atlab'" %.en c.oose 4,atlab &pplication (@ersion C":ea+Gey();%.is co+e 1ill create sinle ,atlab #D, ser*er t.rou. &cti*ator class" )roram K+ 4matlab"application"sinle4 means sinle ,atlab #D, ser*er for our application" =.en it 1ill try to create anot.er ,atlab, it 1ill 7ust return reference to t.e same ob7ect" #ontrary to t.at 1e coul+ use 4matlab"application4 1.ic. 1ill create anot.er instance of ,atlab any time &cti*ator"#reateKntance met.o+ 1ill be execute+" Kn more complex applications or for 1eb applications or ot.er prorams 1.ic. run for lon time it may creates bi memory leaJs since : instance cost aroun+ ''< ,b (on E; bit =in+o1s C an+ ,atlab >'