Main Content

Call MATLAB Function with Struct Output

This example shows how to package a MATLAB® function that processes data and returns a struct array, and deploy it with a .NET application written in C#.

Prerequisites

  1. Create a new work folder that is visible to the MATLAB search path. This example uses C:\Work as the new work folder.

  2. Install MATLAB Runtime on Windows® and on additional platforms where you plan on running your .NET application. For details, see Download and Install MATLAB Runtime.

  3. For Linux® and macOS platforms, after installing MATLAB Runtime, you need to set the LD_LIBRARY_PATH and DYLD_LIBRARY_PATH environment variables respectively. For more information, see Set MATLAB Runtime Library Paths for Deployment.

  4. 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.

Create MATLAB Function

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

function [outputStruct, message] = calculateStatistics(data)
    
    % Calculate statistics
    outputStruct.mean = mean(data);
    outputStruct.median = median(data);
    outputStruct.stdDev = std(data);
    
    % Create a message string
    message = 'Statistics calculated successfully.';
end

Test the MATLAB function at the command prompt.

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
[stats, msg] = calculateStatistics(data)
stats = 
  struct with fields:

      mean: 5.5000
    median: 5.5000
    stdDev: 3.0277
msg =
    'Statistics calculated successfully.'

Create .NET Assembly

Create a .NET assembly using the compiler.build.dotNETAssembly function.

buildResults = compiler.build.dotNETAssembly("calculateStatistics.m",...
Interface="mwarray",...
Verbose="on", ...
AssemblyName="MATLAB.Compiler.SDKFunctions", ...
ClassName="MATLABFunctions", ...
OutputDir=".\output")

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. 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.

P:\MATLAB\WORK\OUTPUT
    buildresult.json
    GettingStarted.html
    includedSupportPackages.txt
    MATLABFunctions.cs
    MATLABFunctionsNative.cs
    mccExcludedFiles.log
    readme.txt
    requiredMCRProducts.txt
    SDKFunctions.dll
    SDKFunctions.xml
    SDKFunctionsNative.dll
    SDKFunctionsNative.xml
    SDKFunctionsVersion.cs
    SDKFunctions_overview.html
    unresolvedSymbols.txt

No subfolders exist

Integrate MATLAB Code into .NET Application

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

  2. At the command line, type:

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

    This creates a folder named ConsoleApp that has the following contents:

    • obj folder

    • ConsoleApp.csproj project file

    • Program.cs C# source file

  3. Open the project file in a text editor.

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
      </PropertyGroup>
    
    </Project>

    Add the following references to the project using the <ItemGroup> tag:

    • SDKFunctions.dll .NET assembly file created by the compiler.build.dotNETAssembly function.

    • MWArray.dll .NET assembly file dependency.

      If MATLAB is installed on your system

      • matlabroot\toolbox\dotnetbuilder\bin\win64\netstandard2.0\MWArray.dll

      If MATLAB Runtime is installed on your system

      • <MATLAB_RUNTIME_INSTALL_DIR>\toolbox\dotnetbuilder\bin\win64\netstandard2.0\MWArray.dll

    Once you add the references, your project file should resemble the following:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>
    
        <ItemGroup>
        <Reference Include="SDKFunctions">
          <HintPath>P:\MATLAB\work\output\SDKFunctions.dll</HintPath>
    	  <!--Path to .NET Assembly created by compiler.build.dotNETAssembly function-->
        </Reference>
        <Reference Include="MWArray">
          <HintPath>C:\Program Files\MATLAB\R2026a\toolbox\dotnetbuilder\bin\win64\netstandard2.0\MWArray.dll</HintPath>
    	  <!--Path to MWArray.dll in the MATLAB-->
        </Reference>
      </ItemGroup>
    </Project>
  4. Replace the code in the Program.cs C# file with the following code:

     Program.cs

  5. At the command line, build your project by typing:

    dotnet build ConsoleApp.csproj

Run C# Application

For testing purposes, you can run the application from MATLAB command prompt. This does not require a MATLAB Runtime. At the MATLAB command prompt, navigate to the directory containing the executable, and run your application by entering:

!dotnet run
The application displays the magic square matrix.
Executing MATLAB function to calculate statistics...
Mean: 3
Median: 3
Standard Deviation: 1.5811388300841898
Message: Statistics calculated successfully.

Integrate Using Visual Studio

As an alternative to the interactive command line approach to creating a .NET application, you can create a .NET application using Microsoft Visual Studio. If you have already created a .NET application using the above instructions, you can skip this section.

  1. Open Visual Studio and create a C# Console App named ConsoleApp. For details, see Create the app section in Create a .NET console application using Visual Studio.

  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. In the Solution Explorer, right-click the project name and select Add > Project Reference. In the Reference Manager window, click Browse and add the following references:

    • SDKFunctions.dll .NET assembly file created by the compiler.build.dotNETAssembly function.

    • MWArray.dll .NET assembly file dependency.

      If MATLAB is installed on your system

      • matlabroot\toolbox\dotnetbuilder\bin\win64\netstandard2.0\MWArray.dll

      If MATLAB Runtime is installed on your system

      • <MATLAB_RUNTIME_INSTALL_DIR>\toolbox\dotnetbuilder\bin\win64\netstandard2.0\MWArray.dll

  5. Build the application.

See Also

| |

Topics