How do I write an array to a binary file?

31 次查看(过去 30 天)
I am trying to save an 3x30 array to a binary file. I managed to save the dara, but so far it adds up the array to one(1x90). Any suggestions on how to solve that? Thanks!
  1 个评论
Rik
Rik 2023-7-17
What format do you need for your file? That format will need a way to indicate the size of the array.

请先登录,再进行评论。

回答(2 个)

Menika
Menika 2023-7-17
Hi,
To save a 3x30 array to a binary file without reshaping it into a 1x90 array, you can use the fwrite function in MATLAB. You can refer to fwrite for doing the same.
Hope it helps!

Walter Roberson
Walter Roberson 2023-7-17

"binary file" means different things to different people.

The standardized "binary" formats that inherently support recording array sizes as well as array content, are typically a bit complex (because they have to be flexible). For example xlsb files are standardized but not internally simple. xlsx files turn out to be directories of text XML files that have been compressed. hdf5 files are pretty complicated and often slow in real use. cdf files require that you worry about defining hierarchies of attributes.

For simple arrays, most often programs use unstandardized binary files that are stored in whatever format is most convenient for the task. For fixed size arrays, a program would probably just fwrite() the array, and to read it back would either supply the expected array size to fread() or else would reshape() the vector results of fread to the expected fixed size.

For simple variable size arrays, it is common for programs to first fwrite array size information. But there is no special agreement about how many bytes are allocated to recording each dimension, or if the dimension information is saved as double for easy use, or whether all of the dimensions are recorded or just the number of rows or number of columns (you can deduce the other dimension by finding out the file size and dividing by the bytes per row or per column). Also no special agreement as to whether the number of dimensions is recorded first or if there are a fixed number of dimension slots with unused trailing dimensions set to 0 or set to 1 or set to the maximum integer...

Routine binary files only have whatever internal structure that the writing programs impose.

There were early attempts to standardize representation of binary formats so that reading programs would not have to have the same computer architecture and would not have to know ahead of time what the representation was. Standards such as XDR. I can count on one finger the number of times in several decades that I have seen XDR used for anything other than unix remote system calls.

类别

Help CenterFile Exchange 中查找有关 Low-Level File I/O 的更多信息

标签

产品


版本

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by