How do I save a MWArray object to a file after calling a MATLAB-compiled library in a .NET application?

I have an operational C# application that uses ".dll" libraries compiled through MATLAB R2020b. The libraries work, and they return a "MWArray" object when finished. How can I save this "MWArray" object in a file and then load it back later?

 Accepted Answer

Regarding saving a "MWArray" variable in an external file, it is possible to directly serialize the variable into a file and then deserialize it back.
As an example, assume that the following "MWStructArray" object is created:
MWStructArray myStructArray = new MWStructArray(1, 2, new String[2] { "field1", "field2" });
myStructArray["field1", 1, 1] = new MWCharArray(new string[3] { "Hello world", "Hello world 2", "Hello world 3" });
myStructArray["field2", 1, 1] = (MWNumericArray)(new double[3] { 1, 2, 3 });
myStructArray["field1", 1, 2] = new MWCharArray(new string[2] { "Hello world 4", "Hello world 5"});
myStructArray["field2", 1, 2] = (MWNumericArray)(new double[2] { 4, 5 });
You can directly serialize the object into a file and then deserialize it back with the following code:
Stream SaveFileStream = File.Create("mydata.txt");
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(SaveFileStream, myStructArray);
SaveFileStream.Close();
if (File.Exists("mydata.txt"))
{
    Stream openFileStream = File.OpenRead("mydata.txt");
    BinaryFormatter deserializer = new BinaryFormatter();
    MWStructArray myStructArray2 = (MWStructArray)deserializer.Deserialize(openFileStream);
    openFileStream.Close();
    System.Console.WriteLine(myStructArray2["field2", 1]);
    System.Console.WriteLine(myStructArray2["field2", 2]);
}
The above workflow can be applied to any type of "MWArray" object.

More Answers (0)

Categories

Find more on MATLAB Compiler SDK in Help Center and File Exchange

Products

Release

R2020b

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!