Main Content

Deploy MATLAB Function That Accepts Cell Array as Input Argument to .NET Application

Supported .NET Version: .NET 6.0 or higher

Data API: MATLAB® Data Array for .NET

This example shows how to package a MATLAB function that accepts a cell array as input and deploy it with a .NET application written in C#. The workflow is supported on Windows®, Linux®, and macOS systems. This example uses a workflow based on Windows.

Since R2023a, .NET applications with packaged MATLAB code can be developed and published across Windows, Linux, and macOS platforms. This means it's possible to develop on any one of these platforms and publish to any of the other two. Prior to that release, .NET applications could only be published from Windows to Linux and macOS.

Note that while development and publishing can happen on any platform, there may still be platform-specific nuances and issues. Some libraries or functionalities might behave differently on different platforms, and developers should test their applications thoroughly on the target platform to ensure expected behavior.

Prerequisites

  • Create a new work folder that is visible to the MATLAB search path. This example uses a folder named work.

  • Verify that you have set up a .NET development environment. For details, see Set Up .NET Development Environment.

  • Verify that you have met all of the MATLAB .NET target requirements. For details, see MATLAB Compiler SDK .NET Target Requirements.

  • End users must have an installation of MATLAB Runtime to run the application. For details, see Download and Install MATLAB Runtime.

    For testing purposes, you can use an installation of MATLAB instead of MATLAB Runtime.

  • Verify that you have .NET 6.0 SDK or higher or Microsoft® Visual Studio® 2022 (v17.0 or higher) installed. You can verify whether .NET 6.0 is installed by entering dotnet --info at a system command prompt. You can download a .NET SDK version specific to your operating system from https://dotnet.microsoft.com/download.

Data Management

To exchange data between the deployed MATLAB code and the .NET application, use the MATLAB Data API for .NET. This API is also used by MATLAB Engine. For an overview, see Call MATLAB from .NET. For details, see:

Create MATLAB Function

Create a MATLAB file named computeCellMean.m with the following code:

function outputCell = computeCellMean(inputCell)
    % computeCellMean - Calculate mean values for data in a cell array.
    % This function takes a 2x2 cell array as input. The cell array is expected
    % to contain numeric arrays. It computes the mean of the numeric arrays
    % in the second column of each row and appends these mean values as new
    % elements in the corresponding rows.
    % Inputs:
    %    inputCell - A 2x2 cell array. The first column can contain any data.
    %                The second column should contain numeric arrays for which
    %                the mean is calculated.
    % Outputs:
    %    outputCell - A 2x3 cell array. The first two columns are the same as
    %                 inputCell, and the third column contains the calculated mean
    %                 values.
    
    % Use arguments block to map a MATLAB type to a C# type
    % Cell arrays in MATLAB map to a System.object in C#
    arguments (Input)
        inputCell (2,2) cell
    end

    arguments (Output)
        outputCell (2,3) cell
    end

    % Calculate mean temperature  and mean pressure
    meanTemperature = mean(inputCell{1, 2});
    meanPressure = mean(inputCell{2, 2});

    % Copy inputCell to outputCell and append mean values
    outputCell = inputCell;
    outputCell{1,end+1} = meanTemperature;
    outputCell{2,end} = meanPressure;
end

Established MATLAB users may find the presence of an arguments block unconventional. The arguments block lets you represent C# data types with an equivalent MATLAB type.

Note

MATLABcell arrays map to System.object in C#. For details, see Data Type Mappings Between .NET and Strongly Typed MATLAB Code.

Test the MATLAB function at the command prompt.

% Define the cell array
data = {
    "temperatures", [72, 75, 69, 68, 70];
    "pressures", [30, 29.5, 30.2, 29.9, 30.1]
}

% Call the function
results = computeCellMean(data)
data =
  2×2 cell array
    {["temperatures"]}    {[72 75 69 68 70]}
    {["pressures"   ]}    {1×5 double      }
results =
  2×3 cell array
    {["temperatures"]}    {[72 75 69 68 70]}    {[70.8000]}
    {["pressures"   ]}    {1×5 double      }    {[29.9400]}

Create .NET Assembly Using compiler.build.dotNETAssembly

Create a code archive (.ctf file), from the MATLAB function using the compiler.build.dotNETAssembly function.

buildResults = compiler.build.dotNETAssembly("computeCellMean.m", Interface="matlab-data",...
    Verbose="on", OutputDir=".\output", AssemblyName="CellStats")

Although supplying an assembly name via the AssemblyName property isn't mandatory, it's highly recommended. Doing so results in a cleaner namespace for the generated .NET assembly and C# file. In its absence, a root namespace named example is automatically appended to the sub-namespace, leading to a cluttered and potentially confusing namespace structure.

The function produces a suite of files, as enumerated below, and places them in the specified output directory. Among these, the key files utilized during the integration process are the code archive (.ctf file) containing the MATLAB code, a C# (.cs) code file, and a .NET assembly (.dll file). For information on the other files, see Files Generated After Packaging MATLAB Functions.

P:\MATLAB\WORK\OUTPUT
│   CellStats.csproj
│   CellStats.ctf
│   CellStats.deps.json
│   CellStats.dll
│   GettingStarted.html
│   includedSupportPackages.txt
│   mccExcludedFiles.log
│   readme.txt
│   requiredMCRProducts.txt
│   unresolvedSymbols.txt
│
└───strongly_typed_interface
        computeCellMean.cs

To finalize integration, you can choose one of two options:

  • Use the CellStats.ctf code archive file in conjunction with the computeCellMean.cs C# code file.

  • Use the CellStats.ctf code archive file in conjunction with the CellStats.dll .NET assembly file.

Upon inspection, you notice that the function also generates a CellStats.csproj project file. This file is generated specifically to create the corresponding CellStats.dll .NET assembly file. However, it should not be mistaken as a template for your .NET project and must not be used in that context.

This example employs the first integration option to illustrate type mapping mechanics. Relevant guidance for using the second option is interjected at pertinent stages of the workflow.

You can inspect the content of the C# code file below:

 computeCellMean.cs

In the computeCellMean.cs C# code file, the MATLAB function's cell argument specification maps its C# equivalent, System.object. This is usually aliased as object and [,] denotes a two-dimensional array.

    arguments (Input)
        inputCell (2,2) cell
    end
   
object[,] inputCell 
    arguments (Output)
        outputCell (2,3) cell
    end
    public static void computeCellMean(MATLABProvider _matlab, 
                        object [,] inputCell,  out object [,] outputCell){
        dynamic _dynMatlab = _matlab;
        outputCell = 
        (object [,])_dynMatlab.computeCellMean(new RunOptions(nargout:1),
         inputCell);
    }

Integrate MATLAB Code into .NET Application

You can finalize the integration process in your preferred C# development environment, including a text editor along with the .NET SDK Command Line API, or alternatives such as Microsoft Visual Studio on Windows and macOS. This example shows you how to complete the integration using both options. For details, see Set Up .NET Development Environment.

Use .NET SDK Command Line API to Build Application

If you are using Microsoft Visual Studio, see Use Microsoft Visual Studio to Build Application (Windows).

  1. Open the command prompt in Windows and navigate to the work folder being used in this example.

  2. At the command line, enter:

    dotnet new console --framework net6.0 --name CellConsoleApp

    This command creates a folder named CellConsoleApp that contains the following:

    • obj folder

    • CellConsoleApp.csproj project file

    • Program.cs C# source file

  3. Copy the following files produced by the compiler.build.dotNETAssembly function to the project folder created by dotnet new, alongside the Program.cs C# application code file:

    • .cs C# wrapper files from the ...\work\output\strongly_typed_interface\ directory.

    • CellStats.ctf code archive from the ...\work\output directory.

  4. Edit the project to add assembly dependencies and the CellStats.ctf code archive file generated by the compiler.build.dotNETAssembly function.

    1. Open the project file in a text editor and include the following assemblies using a <Reference> tag within the <ItemGroup> tag of the project:

      • MathWorks.MATLAB.Runtime.dll

      • MathWorks.MATLAB.Types.dll

       Windows Paths

       Linux and macOS Paths

      Note

      If you use the CellStats.dll .NET assembly generated by the compiler.build.dotNETAssembly function instead of the C# code file, include that as a reference within the same <ItemGroup> tag.

    2. Include the CellStats.ctf code archive file as a content file to the project.

      • Add the CellStats.ctf code archive file as a content file within the <ItemGroup> tag.

      • Add the tag CopyToOutputDirectory and set it to Always. This step ensures that the CellStats.ctf file is copied to the output folder during the build process. This means that when you build your project, this file is in the same directory as your built .exe file.

      • Add the tag CopyToPublishDirectory and set it to Always. This step ensures that the CellStats.ctf file is copied to the cross-platform folder to which this project is published.

    Once you add the assembly dependencies and include CellStats.ctf as a content file, your project file looks like the following:

     CellConsoleApp.csproj (Windows)

     CellConsoleApp.csproj (Linux)

     CellConsoleApp.csproj (macOS)

    Note

    If you choose to use the CellStats.dll .NET assembly—generated by compiler.build.dotNETAssembly—over the C# code file, remember to uncomment the reference tags to the CellStats.dll in the project file. This change ensures your project correctly uses the .dll file.

  5. Replace the code in the Program.cs C# file with the following code:

     Program.cs

    Note

    While developing and operating on macOS systems, transition the code from the Main method into a new function named MainFunc. Subsequently, invoke MATLABRuntime.SetupMacRunLoopAndRun from within the Main method and pass MainFunc along with the command-line arguments as parameters. MATLABRuntime.SetupMacRunLoopAndRun is integral for macOS environments because it lets MATLAB interact with the Core Foundation Run Loop (CFRunLoop), a macOS-specific mechanism for handling events such as user inputs or timer events. For details, see MathWorks.MATLAB.Runtime.MATLABRuntime.

  6. At the command line, build your project by entering:

    dotnet build CellConsoleApp.csproj

Run C# Application

For testing purposes, you can run the application from MATLAB command prompt. This does not require a MATLAB Runtime installation.

At the MATLAB command prompt, navigate to the directory containing the executable, and run your application by entering:

!dotnet run

The application displays the mean values.

INPUT
temperatures     [72.00, 75.00, 69.00, 68.00, 70.00]
pressures        [30.00, 29.50, 30.20, 29.90, 30.10]

OUTPUT
temperatures      [72.00, 75.00, 69.00, 68.00, 70.00]          70.80
pressures         [30.00, 29.50, 30.20, 29.90, 30.10]          29.94

Note

When you're ready to deploy this application, ensure the target system has MATLAB Runtime installed. For details, see Download and Install MATLAB Runtime. On Linux and macOS systems, you must set the LD_LIBRARY_PATH and DYLD_LIBRARY_PATH runtime paths respectively, prior to running your application. For details, see Set MATLAB Runtime Path for Deployment.

Use Microsoft Visual Studio to Build Application (Windows)

  1. Open Microsoft Visual Studio and create a C# Console App named CellConsoleApp.

  2. Choose .NET 6.0 (Long-term support) as the framework.

  3. Swap out the default-generated source code in the Program.cs file with the specific source code provided in the Program.cs file found on this example page.

  4. Choose one of two options:

    • To incorporate the computeCellMean.cs C# code file generated by the compiler.build.dotNETAssembly function, navigate to Solution Explorer, right-click your project, and select Add > Existing Item. Use the dialog box to find and add the computeCellMean.cs C# code file.

    • If you prefer to use the CellStats.dll .NET assembly produced by the compiler.build.dotNETAssembly function, right-click your solution in Solution Explorer and choose Edit Project File. Here, you'll need to add a reference to the CellStats.dll file within the existing <ItemGroup> tag.

    View one of the above-listed project files as a reference.

  5. Add the following assembly dependencies:

    • MathWorks.MATLAB.Runtime.dll

    • MathWorks.MATLAB.Types.dll

     Location of Assembly Dependencies

  6. Add the CellStats.ctf code archive file as a content file to the project. Right-click your project in Solution Explorer and select Add > Existing Item. In the dialog box, browse for the file and add the file.

  7. Right-click the CellStats.ctf file in Solution Explorer and select Properties. In the Properties window, set Build Action to Content and Copy to Output Directory to Copy always.

  8. Right-click your project in Solution Explorer and select Edit Project File. The CellConsoleApp.csproj project file opens in the editor. Add the <CopyToPublishDirectory> tag right below the <CopyToOutputDirectory> tag and set it to Always. The edited portion of the CellConsoleApp.csproj project file looks as follows:

    ...
    <ItemGroup>
        <Content Include="CellStats.ctf">
          <CopyToOutputDirectory>Always</CopyToOutputDirectory>
          <CopyToPublishDirectory>Always</CopyToPublishDirectory>
        </Content>
    </ItemGroup>
    ...

  9. On the menu bar, choose Build and choose Build Solution to build the application within Visual Studio.

    The build process generates an executable named CellConsoleApp.exe.

  10. Run the application from Visual Studio by pressing Ctrl+F5. Alternatively, you can execute the generated executable from a system terminal:

    > cd C:\work\CellConsoleApp\CellConsoleApp\bin\Debug\net6.0
    > CellConsoleApp.exe

    The application returns the same output as the sample MATLAB code.

    INPUT
    temperatures     [72.00, 75.00, 69.00, 68.00, 70.00]
    pressures        [30.00, 29.50, 30.20, 29.90, 30.10]
    
    OUTPUT
    temperatures      [72.00, 75.00, 69.00, 68.00, 70.00]          70.80
    pressures         [30.00, 29.50, 30.20, 29.90, 30.10]          29.94

    Tip

    • If you are unable to build your application, change the solution platform from Any CPU to x64.

    • If you are unable to run your application from Visual Studio, open the Developer Command Prompt for Visual Studio and start Visual Studio by entering devenv /useenv. Then, open your project and run your application.

See Also

| |

Related Topics

External Websites