Main Content

Start MATLAB Session from .NET

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 these MathWorks.MATLAB.Engine.MATLABEngine methods to start MATLAB:

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

Add using statements for:

  • MathWorks.MATLAB.Engine

  • MathWorks.MATLAB.Types

  • MathWorks.MATLAB.Exceptions

Start MATLAB with the -nosplash 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("-nosplash")) {
                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<MATLABEngine> startMatlab1 = MATLABEngine.StartMATLABAsync();
            Task<MATLABEngine> 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

Related Topics