save a 2D array in .mat file

Hello everybody.
I have a source program in C++ that produces a two dimensional array. Is there a way to save the result in a .mat file that can be opened in matlab? Thanks for your help
Last edited on
You would likely get better help if you were to ask the people at Matlab about their file format.
Thanks anyway. The source code is in C ++, I thought about creating a file with ofstream but the result is not readable. I will try to ask the matlab team.
Why do you want to do this, @mariagrazia?

If you are doing data analysis then stay within c++. If you are plotting things then you could write a text file and read it into either matlab or python. you DON'T need the specialised .mat format.
The goal is to get an .m file that shows the contents of the array created in C ++. The creator array as a vector of vectors, contains binary data. Is there any way to get a matlab readable file? is it correct to use ofstream?
Last edited on
Search the web: matlab .mat file format
MathWorks explains the file format here: https://www.mathworks.com/help/pdf_doc/matlab/matfile_format.pdf

Of course, only a subset of this is needed to produce the file needed for a two-dimensional array of numbers.

Page 13 shows an example of a 2x2 numeric array. First just focus on write the 2x2 case (make sure you use ofstream with binary mode set). Then, once you study this, I imagine you can adjust it to allow for arbitrary MxN dimensions.

I thought about creating a file with ofstream but the result is not readable.
Show us what you tried and somebody might be able to explain what's wrong with it. Note that writing in a binary format is much different from just using the << stream operator. You'll need to use ofstream.write.
http://www.cplusplus.com/forum/beginner/41234/
https://stackoverflow.com/questions/49492259/writing-binary-data-to-fstream-in-c
http://www.cplusplus.com/articles/DzywvCM9/
Last edited on

In c ++ I wrote some code to create bid_array starting from a particular data set (.TRC).
Then, to get a .mat file I wrote:

typedef std::basic_ofstream<char> ofstream;
ofstream outfile;
outfile.open ("datafile.m", ios::out | ios::binary);

for (auto val : bid_array) {
outfile.write(reinterpret_cast<const char *>(&val), sizeof(int));
if (outfile.bad()) {
throw std::runtime_error("Failed to write to outfile!");
}
}

but I get a file with strange characters!
Thanks you.
Why can't you use the mat-file interface functions to produce the file?

When writing a file as binary, you will see strange chars when the file as viewed as a text file. That's normal and expected. To see the actual content of these files you need something like a hex viewer/editor which allows you to see/edit the file contents in hex/octal/binary etc.

Note that the typedef statement is not required.
Last edited on
Topic archived. No new replies allowed.