Menu

Usage Examples

Tobias

Q: How do I load data using this library?

A: First, you might want to get a reference to your matlab variable:

var mfr = new MatFileReader(fileName); 
MLArray mlArrayRetrieved = mfr.GetMLArray("my_array");

Second, you need to find out of which type mlArrayRetrieved really is (as MLArray is only a base class) and you cast into the real type. Depending on the real type there are different methods/properties that represent the data.

Q: I know that the data is double array, how can I cast the MLArray type into MLDouble type?

A: Let's assume you were running Matlab and you created a "mydata.mat" file containing a 1x10 double matrix. You used these Matlab statements:

squares = [1:10].^2 
save('mydata.mat', 'squares')

Complete example: You can then use the following C# code to get this data into a .NET double array:

namespace csmatio_test 
{ 
    using System; 
    using csmatio.io; 
    using csmatio.types;

    class Program 
    {
        // this array receives the matlab data 
        static double[] squares;

        static void Main(string[] args) 
        { 
            // create a reader for the file 
            MatFileReader mfr = new MatFileReader("mydata.mat");

            // get a reference to our matlab 'squares' double matrix 
            MLDouble mlSquares = (mfr.Content["squares"] as MLDouble); 
            if (mlSquares != null) 
            { 
                // now get the double values 
                double[][] tmp = mlSquares.GetArray(); 
                squares = tmp[0]; 
            } 
        } 
    } 
}

Q: How to read the content of a three-dimensional double array ?

A: So lets assume we have a 220x180x33 double array called "cube" and we want to read what is in Matlab syntax "cube(7,18,29)":

    // get a reference to our matlab 'cube' double matrix 
    MLDouble mlCube = (mfr.Content["cube"] as MLDouble); 
    if (mlCube != null) 
    { 
        // calculate the index of our element 
        idx = 7-1 + (18-1)*220 + (29-1)*180*220; 
        // now get the double value 
        double value = mlCube.Get(idx); 
    }

The same goes for arrays with four or more dimensions.

Q: How to create a matlab 2D double array and save it to a mat file?

A: There are several ways to do this.
Let's assume you've got the array values in a .NET double[][] array:

    double[][] data3x3 = new double[3][];
    data3x3[0] = new double[] { 100.0, 101.0, 102.0 }; // first row
    data3x3[1] = new double[] { 200.0, 201.0, 202.0 }; // second row
    data3x3[2] = new double[] { 300.0, 301.0, 302.0 }; // third row

From this you can create a Matlab double array named "Matrix_3_by_3" with one line of code:

    MLDouble mlDoubleArray = new MLDouble("Matrix_3_by_3", data3x3);

Now save this array to mat file "data.mat":

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

Q: How to create a 3D double array?

A: You can easily create an empty 3D double array as follows:

    // init 3D double array (2x3x4 elements) 
    int[] dims = new int[] { 2, 3, 4 }; 
    MLDouble array3Dim = new MLDouble("cube", dims);

Q: I am able to create the 3D array - how to populate the data inside?

A: Once you created the 3D array, then use: array.Set(value, row_ind, col_index).
For example, your 3D array is m*n*3:

  • for 1st dimension, use array.Set(value, row_ind, col_index);
  • for 2nd dimension, use array.Set(value, row_ind, col_index+n);
  • for 3rd dimension, use array.Set(value, row_ind, col_index+2n)

Q: How to read Matlab structs?

A: Reading from structs was buggy in the original 2007 version. Make sure you use the latest csmatio version.

The csmatio source code contains a demo file named "struct.mat". Here is some demo code to read the content of this mat file:

    // create a reader for the file 
    MatFileReader mfr = new MatFileReader("struct.mat");

    // get a reference to the matlab struct named 'X' 
    MLStructure mlStruct = mfr.Content["X"] as MLStructure;

    // print the names of the struct members (csmatio rev.18 or higher)
    foreach (string key in mlStruct.Keys)
    {
        Console.WriteLine(key); // "var", "w", "Version"
    }

    // get references to some struct member objects 
    MLChar mlVersion = mlStruct["Version"] as MLChar; 
    MLDouble mlW = mlStruct["w"] as MLDouble;

    // get values from struct members 
    string version = mlVersion.GetString(0); // "1.0.5.23354" 
    double w = mlW.Get(0); // 3874.0

Q: I have a variable of type 1xN struct array with fields: spin(3x3). How do I get the data?

A: Here is the example:

    // create a reader for the file 
    MatFileReader mfr = new MatFileReader("structarray.mat");

    // get a reference to the matlab struct array named 's1' 
    MLStructure mlStruct = mfr.Content["s1"] as MLStructure;

    for (int i = 0; i < mlStruct.Size; ++i) 
    { 
        // get reference to struct member 'spin' (3x3 double array) 
        MLDouble mlSpin = mlStruct["spin", i] as MLDouble; 

        // get values 
        double[][] spin = mlSpin.GetArray(); 
    }

Q: I need to write some nested vars in .mat file ?

A: Le me give you a basic example how to create nested Matlab vars (aka structs) with this lib. Suppose we have following C# struct:

    public struct Score 
    { 
        public string Name; 
        public double Value; 
    }

Now we initialize a struct object named highscore of that type:

    Score highscore; 
    highscore.Name = "David"; 
    highscore.Value = 47.3;

Here is how you represent this struct object in the mat file:

    // create a corresponding MATLAB structure
    MLStructure structure = new MLStructure("highscore", new int[] { 1, 1 });

    // create a MATLAB char and double variable and add it to the structure
    MLChar scoreName = new MLChar("", highscore.Name); 
    MLDouble scoreValue = new MLDouble("", new double[] { highscore.Value }, 1); 
    structure["Name", 0] = scoreName; 
    structure["Value", 0] = scoreValue;

    // save the structure as mat file using MatFileWriter
    List<MLArray> mlList = new List<MLArray>(); 
    mlList.Add(structure); 
    MatFileWriter mfw = new MatFileWriter("data.mat", mlList, false);

Now lets create a struct array. First we initialize some data:

    Score[] highscores = new Score[3];
    int idx;
    idx = 0;
    highscores[idx] = new Score();
    highscores[idx].Name = "Tom";
    highscores[idx].Value = 41;
    idx = 1;
    highscores[idx] = new Score();
    highscores[idx].Name = "Dick";
    highscores[idx].Value = 43;
    idx = 2;
    highscores[idx] = new Score();
    highscores[idx].Name = "Harry";
    highscores[idx].Value = 47;

Here is how you write this data into a mat file:

    MLStructure mlStructArr = 
        new MLStructure("highscores", new int[] { highscores.Length, 1 });
    for (int i = 0; i < highscores.Length; ++i)
    {
        mlStructArr["Name", i] = new MLChar("", highscores[i].Name);
        mlStructArr["Value", i] = new MLDouble("", new double[] { highscores[i].Value }, 1);
    }

    // save to mat file using MatFileWriter
    List<MLArray> mlList = new List<MLArray>(); 
    mlList.Add(mlStructArr ); 
    MatFileWriter mfw = new MatFileWriter("data.mat", mlList, false);

In Matlab you can use the data in a number of ways:

load('data.mat')
winner = highscores(3); % { Name = 'Harry', Value = 47 }
highscores(2).Name; % 'Dick'
scoreValues = [highscores.Value]; % 41 43 47

Related

Discussion: The creation of the two-dimentional MLDouble array
Discussion: Welcome!
Discussion: Structure Array
Discussion: CSMatio to/from datetable
Tickets: #3
Wiki: Home

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.