Start MATLAB Session from .NET - MATLAB & Simulink (original) (raw)

Main Content

For information on how to set up and build .NET engine programs, see Test Your .NET Development Environment.

You can start a MATLAB® session from your .NET program synchronously or asynchronously. Use theseMathWorks.MATLAB.Engine.MATLABEngine methods to start MATLAB:

You should always terminate the MATLAB session using the TerminateEngineClient method.

Add using statements for:

Start MATLAB with the -nodesktop Option

Start MATLAB and display starting and closing messages.

using MathWorks.MATLAB.Engine; using MathWorks.MATLAB.Exceptions; using MathWorks.MATLAB.Types; using System;

namespace MathWorks.MATLAB.Engine.ConsoleExamples { public class Program {
public static void Main(string[] args) { Console.Write("Starting MATLAB... "); using (dynamic eng = MATLABEngine.StartMATLAB("-nodesktop")) { Console.WriteLine("done."); eng.disp(new RunOptions(nargout: 0), "Hello. Closing MATLAB..."); } // Call when you no longer need MATLAB Engine in your application. MATLABEngine.TerminateEngineClient(); Console.WriteLine("done."); } } }

Asynchronously Start Two MATLAB Sessions

Asynchronously start two MATLAB sessions, then wait for them to start before proceeding.

using MathWorks.MATLAB.Engine; using MathWorks.MATLAB.Exceptions; using MathWorks.MATLAB.Types; using System.Threading; using System.Threading.Tasks; using System;

namespace MathWorks.MATLAB.Engine.ConsoleExamples { public class Program { public static async Task Main(string[] args) { // StartMATLABAsync Task startMatlab1 = MATLABEngine.StartMATLABAsync(); Task startMatlab2 = MATLABEngine.StartMATLABAsync();

        Console.WriteLine("Two MATLAB sessions are starting in the background.");
        Console.WriteLine("Wait for both to start before continuing.");
        await Task.WhenAll(startMatlab1, startMatlab2);
        Console.WriteLine("Two MATLAB sessions started.");
        MATLABEngine.TerminateEngineClient();
    }
}

}

See Also

MathWorks.MATLAB.Engine.MATLABEngine

Topics