Search code examples
c#.netmatlabmultidimensional-arraymatio

How can I convert a 3D C# array to a 3D Matlab array as an importable .mat file?


I have a 3D double array double[,,] surfaceData = new double[5, 304, 304]; that I then populate with nested for loops. It works great in C#, but how do I convert it to a .mat Matlab-readable file?

I am using csmatio. I can output .mat files with it:

List<MLArray> mlList = new List<MLArray>();
mlList.Add(mlDouble);
MatFileWriter mfw = new MatFileWriter("SurfaceDataTest.mat", mlList, false);

...where mlDouble is an MLDouble object in csmatio. This is no issue. The issue is populating that mlDouble when I can't directly reference three indeces (mlDouble[4,3,60] for example). Instead, the usage guidlines suggest I populate my 3D array like so...

screenshot of guide

I have tried many nested for loops and haven't yet found a solution.

Here is a messy example:

for(int i = 0; i < 304; i++) 
{
    for(int j = 0; j < 304; j++) 
    {
        for(int k = 0; k < 5; k++) 
        {
            mlDouble.Set(surfaceData[k, j, i], i, j * k);
        }
    }
}

Solution

  • In case this helps anyone, I found it easier to use MatFileHandler instead of csmatio.

    In MatFileHandler, simply define a DataBuilder:

    DataBuilder builder = new DataBuilder();
    

    Define a MatLab variable with a string name and the C# object:

    var matVar = builder.NewVariable("<VariableNameForML>", csharpvar);
    

    Create a list of variables you want to add, even if only adding one:

    List<IVariable> matList = new List<IVariable>();
    matList.Add(matVar);
    

    Then:

    var matFile = builder.NewFile(matList);
    
    using (var fileStream = new FileStream("SurfaceData.mat", FileMode.Create))
    {
        var writer = new MatFileWriter(fileStream);
        writer.Write(matFile);
    }
    

    Hope this helped anyone in the same position as me :)