Saving *.mat files using C#

10 views (last 30 days)
Yoni Stern
Yoni Stern on 13 Nov 2022
Answered: Harsh on 24 Jul 2025
Hi all,
I have a simple 3D array of doubles that I need to save as a *.mat file, so that MATLAB (2018B) can later import it and work with it. I am looking for the equivalent in C# that may help me do the same.
My programmer tried to do so by saving the 3D array as binary, but when I try to UIOpen them into MATLAB I get:
"Error using load. Unable to read MAT-file
C:\...\Max_Temp.mat. Not a binary MAT-file. Try load -ASCII to read as text."
When I use a mat file which I saved using regular "save" command in MATLAB, it imports it with no problems.
Can anybody help my programmer use the right format so that the saved mat file is recognized by MATLAB?
Thanks!

Answers (1)

Harsh
Harsh on 24 Jul 2025
The most reliable approach is to use MATLAB's official .NET interface. This requires having MATLAB installed on the machine where your C# code runs. Here's an example script to achieve your task-
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
// Create your 3D array
double[,,] myArray = new double[10, 20, 30]; // Your actual data here
// Convert to MATLAB array
MWNumericArray matlabArray = new MWNumericArray(myArray);
// Save to .mat file
MATLAB.save("C:\\path\\to\\your\\file.mat", "variableName", matlabArray);
You can find more information about this approach in the official documentation for MATLAB Engine API for .NET - https://www.mathworks.com/help/compiler_sdk/dotnet_assemblies.html

Categories

Find more on Data Import and Analysis in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!