Contenido principal

Test Your .NET Development Environment

R2026b

MATLAB® engine API for .NET ships with example C# code to help test your environment and become familiar with using the engine API.

To open the folder containing the example code, run this command in the Command Window, where matlabroot is the path returned by the MATLAB matlabroot command:

fullfile(matlabroot,"extern","examples","engines","dotnet")

Folder Contents

  • dotnet_engine_examples.sln — Microsoft® Visual Studio® project files.

  • Program.cs — Console application that runs all examples in the project.

    MainWindow.xaml.cs — Windows® GUI application that calculates a factorial based on user input.

  • .cs files — C# example source files.

  • README — Text file that describes how to build and run the examples using Visual Studio.

Examples Overview

The examples show how to:

  • Call MATLAB functions from C#.

    /* Copyright 2022 The MathWorks, Inc. */
    
    /*
     * This file contains basic examples of calling MATLAB functions from C#, including:
     * - Calling MATLAB functions from a MATLABEngine instance.
     * - Invoking MATLAB package functions from a MATLABEngine instance.
     * - Passing C# types as arguments to MATLAB functions.
     * - Converting MATLAB return values to C# types.
     */
    using MathWorks.MATLAB.Types;
    using System;
    
    namespace MathWorks.MATLAB.Engine.ConsoleExamples
    {
        public class BasicExample
        {
            public static void Run(dynamic eng)
            {
                // Call a MATLAB function with a single output
                Console.Write("Calling sqrt(2)... ");
                double sqrt = eng.sqrt(2.0);
                Console.WriteLine(sqrt);
    
    
                // Call a MATLAB package function
                Console.Write("Calling matlab.desktop.commandwindow.size()... ");
                double[] size = eng.matlab.desktop.commandwindow.size();
                Console.WriteLine("[{0}]", string.Join(',', size));
    
    
                // Call a MATLAB function with zero outputs
                Console.Write("Calling disp(\"Hello, MATLAB!\")... ");
                RunOptions opts = new RunOptions() { Nargout = 0 };
                eng.disp(opts, "Hello, MATLAB!");
    
    
                // Call a MATLAB function with two outputs
                Console.Write("Calling weekday(\"10-10-2010\")... ");
                opts = new RunOptions() { Nargout = 2 };
                (double, string) result = eng.weekday(opts, "10-10-2010");
                Console.WriteLine(result);
                
            }
        }
    }
  • Handle exceptions.

    /* Copyright 2022 The MathWorks, Inc. */
    
    /*
     * This file contains examples of exception handling, which may be thrown if:
     * - The application cannot find or connect to MATLAB.
     * - A error occurs when executing a MATLAB function.
     * - An unsupported .NET type is used as an argument to a MATLAB function.
     * - A MATLAB type cannot be converted to a particular .NET type.
     */ 
    using MathWorks.MATLAB.Exceptions;
    using MathWorks.MATLAB.Types;
    using System;
    
    namespace MathWorks.MATLAB.Engine.ConsoleExamples
    {
        public class ExceptionExample
        {
            public static void Run(dynamic eng)
            {
                // If MATLAB is not available, a MATLABNotAvailableException will be thrown.
                const string nameThatDoesNotExist = "unknown_matlab";
                Console.Write("Connecting to MATLAB {0}... ", nameThatDoesNotExist);
                try
                {
                    eng = MATLABEngine.ConnectMATLAB(nameThatDoesNotExist);
                }
                catch (MATLABNotAvailableException)
                {
                    Console.WriteLine("MATLAB {0} does not exist.", nameThatDoesNotExist);
                }
    
    
                // If a runtime error occurs, a MATLABExecutionException will be thrown. 
                // The error text is forwarded to Console.Error by default. 
                // This behavior may be modified with the Error property of a RunOptions instance.
                Console.Write("Calling MATLAB function unknown_function... ");
                try
                {
                    eng.unknown_function();
                }
                catch (MATLABExecutionException) { }
    
    
                // If a .NET type cannot be converted to a MATLAB type,
                // an UnsupportedTypeException will be thrown.
                Console.Write("Sending a System.Decimal to MATLAB... ");
                try
                {
                    decimal someUnsupportedData = decimal.One;
                    eng.disp(new RunOptions() { Nargout = 0 }, someUnsupportedData);
                }
                catch (UnsupportedTypeException e)
                {
                    Console.WriteLine(e.Message);
                }
    
    
                // If a MATLAB type cannot be converted to a .NET type,
                // a System.InvalidCastException will be thrown.
                Console.Write("Converting a MATLAB char array to System.Double... ");
                try
                {
                    double notADouble = eng.eval(" 'this is a char array' ");
                }
                catch (InvalidCastException e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
  • Interact with MATLAB objects from a C# application.

    /* Copyright 2022 The MathWorks, Inc. */
    
    /*
     * This file contains examples of how to interact with MATLAB objects from
     * a C# application using the `dynamic` keyword. Examples include:
     * - Calling a MATLAB class constructor.
     * - Accessing properties on a MATLAB class.
     * - Invoking methods on a MATLAB class.
     */
    using MathWorks.MATLAB.Types;
    using System;
    
    namespace MathWorks.MATLAB.Engine.ConsoleExamples
    {
        public class ObjectExample
        {
            public static void Run(dynamic eng)
            {
                // Change the directory so our class is visible to MATLAB
                Console.Write("Changing working folder... ");
                string oldDir = eng.pwd();
                string newDir = eng.fullfile(eng.matlabroot(), "extern", "examples", "engines", "dotnet", "console");
                RunOptions opts = new RunOptions() { Nargout = 0 };
                eng.cd(opts, newDir);
                Console.WriteLine("Changed to {0}", newDir);
    
    
                // Create a Triangle and assign it to the `dynamic` type
                Console.Write("Creating a Triangle... ");
                double edgeLength = 1;
                dynamic triangle = eng.Triangle(edgeLength, edgeLength);
                Console.WriteLine("Created a 1x1 Triangle.");
    
    
                // Access properties of Triangle
                Console.Write("Changing triangle.Base to 3 and triangle.Height to 4... ");
                triangle.Base = 3.0;
                triangle.Height = 4.0;
                double area = triangle.Area;
                Console.WriteLine("triangle.Area is now {0}", area);
    
    
                // Call methods of Triangle
                Console.Write("Resizing triangle by 10... ");
                opts = new RunOptions() { Nargout = 0 };
                triangle.resize(opts, 10.0);
                area = triangle.Area;
                Console.WriteLine("triangle.Area is now {0}", area);
    
                Console.WriteLine("Displaying triangle...");
                triangle.disp(opts);
    
    
                // Restore the original working directory
                Console.Write("Restoring original working folder... ");
                opts = new RunOptions() { Nargout = 0 };
                eng.cd(opts, oldDir);
                Console.WriteLine("Changed to {0}", oldDir);
            }
        }
    }
  • Interact with MATLAB structs from a C# application.

    /* Copyright 2022 The MathWorks, Inc. */
    
    /*
     * This file contains examples of how to interact with MATLAB structs from
     * a C# application using the `dynamic` keyword and the MATLABStruct data type. 
     *  Examples include:
     * - Creating a MATLABStruct
     * - Calling methods of a MATLABStruct
     * - Passing a MATLABStruct to MATLAB
     */
    using MathWorks.MATLAB.Types;
    using System;
    using System.Collections.Generic;
    
    namespace MathWorks.MATLAB.Engine.ConsoleExamples
    {
        public class StructExample
        {
            public static void Run(dynamic eng)
            {
    
                // Create a MATLABStruct and assign it to the 'dynamic' type
                Console.WriteLine("Creating a MATLABStruct... ");
                MATLABStruct mStruct = new MATLABStruct(("a", 1), ("b", 2));
                dynamic dynamicMStruct = mStruct;
                Console.WriteLine("Created a 1x1 MATLABStruct with 2 fields");
    
    
                // Access fields of a MATLABStruct
                Console.WriteLine("Display values of fields... ");
                double a = mStruct.GetField("a");
                double b = dynamicMStruct.b;
                Console.WriteLine("(a, b): ( {0} , {1})",a, b);
    
    
                // Call methods of MATLABStruct
                Console.WriteLine("Calling methods of MATLABStruct... ");
                int numFields = mStruct.Count();
                bool containsFieldA = mStruct.IsField("a");
                IEnumerable<string> fieldNames = mStruct.GetFieldNames();
                Console.WriteLine("The struct contains {0} fields", numFields);
    
                // Call MATLAB function with a MATLABStruct as input
                eng.disp(new RunOptions(nargout: 0), mStruct);
                
            }
        }
    }
  • Interact with the MATLAB base workspace.

    /* Copyright 2022 The MathWorks, Inc. */
    
    /*
     * This file contains examples for interacting with the MATLAB base workspace, including:
     * - Setting variables in the MATLAB base workspace.
     * - Retrieving variables from the MATLAB base workspace.
     * - Querying the MATLAB base workspace for the existence of variables.
     */
    using MathWorks.MATLAB.Types;
    using System;
    using System.Linq;
    
    namespace MathWorks.MATLAB.Engine.ConsoleExamples
    {
        public class WorkspaceExample
        {
            public static void Run(dynamic eng)
            {
                // Set workspace variables using the MATLABWorkspace dictionary
                Console.Write("Setting workspace variables... ");
                MATLABWorkspace workspace = eng.Workspace;
                workspace["x"] = 3.14;
    
    
                // Set workspace variables using the 'eval' function
                RunOptions opts = new RunOptions() { Nargout = 0 };
                eng.eval(opts, "y = 'this is a char array';");
    
    
                // Display information on the MALTAB base workspace
                int numVars = workspace.Count;
                Console.WriteLine("There are {0} variables in the MATLAB base workspace.", numVars);
    
                string[] varNames = workspace.Keys.ToArray();
                Console.WriteLine("  It contains these variables: {0}", string.Join(", ", varNames));
    
    
                // Get workspace variables using the MATLABWorkspace dictionary
                Console.WriteLine("Retrieving workspace variables... ");
                double valueOfX = workspace["x"];
                string valueOfY = workspace["y"];
                Console.WriteLine("  x == {0}", valueOfX);
                Console.WriteLine("  y == \"{0}\"", valueOfY);
    
    
                // Query for the existence of particular variables
                Console.Write("Querying the value of x... ");
                if (workspace.TryGetValue("x", out valueOfX))
                    Console.WriteLine("x == {0}", valueOfX);
                else
                    Console.WriteLine("x does not exist in the workspace.");
    
                Console.Write("Querying the value of z... ");
                if (workspace.TryGetValue("z", out string valueOfZ))
                    Console.WriteLine("z == {0}", valueOfZ);
                else
                    Console.WriteLine("z does not exist in the workspace.");
            }
        }
    }

Build and Run Examples

To build and run the examples, copy the example files to a writable folder on your path by running these commands in the Command Window:

copyfile(fullfile(matlabroot,"extern","examples","engines","dotnet","dotnet_engine_examples.sln"),".","f")
copyfile(fullfile(matlabroot,"extern","examples","engines","dotnet","console\*.*"),".\console\","f")

If you are on a Windows platform, run this command to copy the Windows GUI application:

copyfile(fullfile(matlabroot,"extern","examples","engines","dotnet","gui\*.*"),".\gui\","f")

Follow these instructions in the README file.

Copyright 2023 The MathWorks, Inc.

These instructions are for compiling and running a C# application
that uses MATLAB Engine API for .NET from the command line.

Projects can also be opened in your favorite IDE.

In these instructions, replace <matlabroot> with the value returned 
by the matlabroot function in MATLAB.


## PREREQUISITES ##

1. Install the latest .NET SDK from https://dotnet.microsoft.com/download
   The full .NET SDK is required, not just the .NET Runtime.

2. Set up environment variables to point to your MATLAB installation.
   Use these environment variable names and paths:

Windows:
  PATH
  <matlabroot>\extern\bin\win64

Apple Silicon:
  DYLD_LIBRARY_PATH
  <matlabroot>/extern/bin/maca64

Linux:
  LD_LIBRARY_PATH
  <matlabroot>/extern/bin/glnxa64:<matlabroot>/sys/os/glnxa64
  
3. Copy the example files to a working directory for example "C:\work".  
   The files that need to be copied are as follows:

Windows:
   dotnet_engine_examples.sln
   all files in the console and gui directories
   
Apple macOS and Linux:
   dotnet_engine_examples.sln
   all files in the console directory

## COMPILING ##

Use the 'dotnet build' command to compile all example projects.
  $> cd C:\work
  $> dotnet build /p:matlabroot=<matlabroot>


## RUNNING ##

Use the 'dotnet run' command to execute a particular example project.
To run the console example:
  $> dotnet run --no-build --project console
  
  
To run the gui example (Windows only):
  $> dotnet run --no-build --project gui

See Also

Topics