Search code examples
c#matlabfwritebinarywriter

Matlab fwrite in C#


I have a piece of code that i am trying to implement in C#. The code writes a file using the frwite command using Matlab. I have tried looking at the documentation and doing some examples to understand how does frwite works. I tried the following but no success.

Here is the code:

line_vectors = [5;10;15;20;25]
sampPeriod=100000;
[filename,permission,machineformat] = fopen(outputfile);
fwrite(outputfile,sampPeriod,'int32');
fwrite(outputfile,line_vectors(:),'float32');

Output using fread():

       160
       134
         1
         0
         0
         0
       160
        64
         0
         0
        32
        65
         0
         0
       112
        65
         0
         0
       160
        65
         0
         0
       200
        65

I tried to implement a similar code in C#:

                using (BinaryWriter writer = new BinaryWriter(file))
                {
                    writer.Write(100000);
                    writer.Write(5);
                    writer.Write(10);
                    writer.Write(15);
                    writer.Write(20);
                }

Output using fread() in Matlab:

   160
   134
     1
     0
     5
     0
     0
     0
    10
     0
     0
     0
    15
     0
     0
     0
    20
     0
     0
     0

If anybody could help me in mapping the fwrite functionality in C#.


Solution

  • If you want all numbers after the 1st to be written as float32, you can indicate the value type for the other values, like this:

    using (BinaryWriter writer = new BinaryWriter(file))
    {
        writer.Write(100000);
        writer.Write(5.0f);
        writer.Write(10.0f);
        writer.Write(15.0f);
        writer.Write(20.0f);
    }
    

    BinaryWriter.Write is an overloaded function, with many possible input types. Depending on the type passed as the input variable, the specific version of the function writes the bytes that represent the value as that type. Since your initial code provided no other information, the default is to assume int, and a 4 byte integer representation was used.