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
Create a new work folder that is visible to the MATLAB search path. This example uses
C:\Workas the new work folder.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.
For Linux® and macOS platforms, after installing MATLAB Runtime, you need to set the
LD_LIBRARY_PATHandDYLD_LIBRARY_PATHenvironment variables respectively. For more information, see Set MATLAB Runtime Library Paths for Deployment.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 --infoat 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 existIntegrate MATLAB Code into .NET Application
Open the command prompt in Windows and navigate to the
workfolder being used in this example.At the command line, type:
dotnet new console --framework net6.0 --name ConsoleAppThis creates a folder named
ConsoleAppthat has the following contents:objfolderConsoleApp.csprojproject fileProgram.csC# source file
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 thecompiler.build.dotNETAssemblyfunction.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>Replace the code in the
Program.csC# file with the following code: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 runExecuting 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.
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.Choose
.NET 6.0 (Long-term support)as the framework.Swap out the default-generated source code in the
Program.csfile with the specific source code provided in theProgram.csfile found on this example page.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 thecompiler.build.dotNETAssemblyfunction.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
Build the application.
See Also
compiler.build.dotNETAssembly | compiler.build.DotNETAssemblyOptions | compiler.package.installer
