3

I have a float array :

float[] samples32array

I need to convert it into a binary file so I can read it in matlab.

Is there any way to do that?

2

3 Answers 3

5

It's simple. First, you should use FileStream and create a file. Then, you can use BinaryWriter, which can write any C# datatype into an underlaying stream, such as a FileStream.

using (FileStream file = File.Create(path))
{
    using (BinaryWriter writer = new BinaryWriter(file))
    {
        foreach (float value in samples32array)
        {
            writer.Write(value);
        }
    }
}

Since the constructor of BinaryWriter accepts the basic type Stream, any stream type can be used. It works for file streams as well as NetworkStream or a MemoryStream etc. It's a very generic class.

And please avoid converting the float[] into a byte[] beforehand as it will allocate memory and this is bad if your array is big (don't know if that's the case for you).

Sign up to request clarification or add additional context in comments.

1 Comment

using System.IO;
3

You can use BinaryWriter to write the data to a file very easily:

foreach (var value in samples32array)
{
    writer.Write(value);
}

Now BinaryWriter is guaranteed to use little-endian format, so in your Matlab call, you should specify a machinefmt value of l to explicitly read it in little-endian format too.

1 Comment

Hello Jon, I use matlab to read the file like this: fid = fopen('myRecordBin.bin', 'r'); fread(fid,inf,'float',4,'l'); Now, I can read it and matlab's workspace show 69222 elements and in the vector it shows: 69222x1 double. But my original float array(and not double) in c# is twice: 138444 elements. Is something wrong with my reading?
1

This SO answer shows a way to convert a float array into a byte array. Then you can use File.WriteAllBytes() method to write it out to a file. How MatLab reads it, though, will be the issue.

I found some documentation for MatLab for the fread command. It looks like is has some arguments that will allow you to define the precision of the read. You may be able to use "float" as the precision value. Though, the is a bit of an educated guess as I am not very familiar with MatLab.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.