How can I save/load a .NET array to a .mat file?

How can I save/load a .NET array to a .MAT file? I always get errors when trying to load the data after it has been saved e.g.
>> dArray = NET.createArray('System.Double', 2);
>> dArray(1) = 1.1;
>> dArray(2) = 2.2;
>> save dArray.mat dArray
>> load('dArray.mat')
Warning: Cannot load an object of class 'Double[]':
No matching constructor signature found.

 Risposta accettata

Helen
Helen il 10 Lug 2025
Modificato: Helen il 10 Lug 2025
Since R2025a, you can save (serialize) .NET objects to a MAT file. For more information, see Save and Load .NET Objects in MAT Files.
Thank you to those who contributed earlier workarounds for previous releases.

Più risposte (2)

It's perhaps kind of a pain, but you could cast the array to a Matlab double array prior to saving and then cast it back to a .NET array after loading. You could do something like
mat_Array = double(dArray);
save dArray.mat mat_Arry
load('dArray.mat');
dArray = NET.convertArray(mat_Array);
Alternatively, you could try to install System.Double into the Global Assembly Cache. See http://msdn.microsoft.com/en-us/library/6axd4fx6.aspx for information on how to do that. That might then allow Matlab to find the constructor for the System.Double[] object, but I'm not sure.
Good luck.
-Eric

3 Commenti

Thanks for the suggestion Eric. This was just a trivial example to illustrate the problem - my 'real world' code uses arrays of .NET objects instantiated from custom .NET classes.
The issue seems to be when saving/loading arrays of .NET objects - it works fine when using single objects.
Best regards
George
What happens if you try to load the MAT file after using NET.addAssembly() to add your NET classes to Matlab's cache?
Another option might be to compile your custom .NET classes such that they are installed into the GAC.
-Eric
Thanks Eric. I am already using NET.addAssembly() and it works perfectly saving/loading a SINGLE object, but it doesn't work for an ARRAY of the same object type.
It looks like MATLAB is confused by the '[]' notation for the arrays and is trying to locate a class called e.g. 'System.Double[]' instead of an array of 'System.Double' objects.
George

Accedi per commentare.

Can you put your .Net array inside a scalar wrapper object? Something like
Public Class ArrayWrapper
Public CustomArray() As CustomClass
End Class
and then try to save an instance of the ArrayWrapper class? Not sure if it will work for you, but I have used a similar work around for a different problem in the past.

Richiesto:

il 9 Apr 2013

Modificato:

il 10 Lug 2025

Community Treasure Hunt

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

Start Hunting!

Translated by