Main Content

Save and Load .NET Objects in MAT Files

You can save and load .NET objects in MAT files by using the save and load functions. To perform the serialization and deserialization, MATLAB® uses the Microsoft® class System.Runtime.Serialization.DataContractSerializer.

Save and Load .NET Object

For example, create and save a .NET object to a MAT file named volume.mat.

NET.addAssembly('System.Speech');
speak = System.Speech.Synthesis.SpeechSynthesizer;
speak.Volume = 100;
save volume.mat speak

Clear the .NET object from the workspace and then load it from the MAT file.

clear
load test.mat
speak
speak = 
  SpeechSynthesizer with properties:

     State: Ready
      Rate: 0
    Volume: 100
     Voice: [1×1 System.Speech.Synthesis.VoiceInfo]

Supported and Unsupported Types

You can save .NET objects of these types:

  • Primitive types

  • Collection types

  • Custom types with parameterless constructors

  • Types with the attribute SerializableAttribute

MATLAB does not support saving .NET objects of these types in MAT files:

  • Multidimensional arrays

  • Object arrays

For more information, see the Microsoft documentation Types Supported by the Data Contract Serializer.

Customizing Serialization

When MATLAB serializes .NET objects, these serialization rules apply:

  • .NET object types default to serializing public fields and properties with get and set methods.

  • The save function ignores read-only fields, properties without get or set methods, and properties with internal or private get or set methods.

However, you can customize the serialization of .NET objects using the attributes DataContractAttribute or DataMemberAttribute. For customization information, see the Microsoft documentation DataContractAttribute Class and DataMemberAttribute Class.

You can also manually write serialization code using the Microsoft classes System.Xml.Serialization.XmlSerializer, System.Runtime.Serialization.DataContractSerializer, or System.Text.Json.JsonSerializer. Serialize your .NET object to a string or byte array, and then save that object to a MAT file.

If you know the types that might be serialized by your .NET object, you can use the attribute KnownTypesAttribute to specify those types. For more information, see the Microsoft documentation DataContractSerializer.KnownTypes Property.

For more information, see the Microsoft documentation Serialization Defaults.

See Also

| |

External Websites