在 Matlab 中读取和写入二进制文件 [英] Read and write from/to a binary file in Matlab

查看:20
本文介绍了在 Matlab 中读取和写入二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 matlab 的了解只是基于需要了解,所以这可能是一个基本问题.然而它来了:

My knowledge of matlab is merely on a need to know basis, so this is probably an elementary question. Nevertheless here it comes:

我有一个文件,其中包含以二进制格式存储的数据(16 位整数).如何将它读入matlab中的向量/数组?如何将这些数据写入 matlab 中的文件?在读取/写入大量数据(千兆字节)时,是否有任何巧妙的调整来提高性能速度?

I have got a file containing data (16-bit integers) stored in binary format. How do I read it into a vector /an array in matlab? How do I write this data to a file in matlab? Is there any smart tweak to increase the performance speed when reading/writing a huge amount of data (gigabytes)?

推荐答案

As Bill the Lizard 写道,您可以使用 fread 将数据加载到向量中.我只想扩展他的答案.

As Bill the Lizard wrote you can use fread to load the data into a vector. I just want to expand a little on his answer.

>> fid=fopen('data.bin','rb') % opens the file for reading
>> A = fread(fid, count, 'int16') % reads _count_ elements and stores them in A.

fopenfread 命令默认为整数的 Little-endian[1] 编码.如果您的文件是大端编码的,您需要将 fread 更改为

The commands fopen and fread default to Little-endian[1] encoding for the integers. If your file is Big-endian encoded you will need to change the fread to

>> A = fread(fid, count, 'int16', 'ieee-be');

另外,如果你想读取整个文件集

Also, if you want to read the whole file set

>> count=inf;

如果您想将数据读入具有 n 列的矩阵,请使用

and if you want to read the data into matrix with n columns use

>> count=[n inf];

写入数据

至于将数据写入文件.命令 fwrite,位于 Bill 的 答案将写入二进制文件.如果要将数据写入文本文件,可以使用 dlmwrite

Writing Data

As for witting the data to a file. The command, fwrite, in Bill's answer will write to a binary file. If you want to write the data to a text file you can use dlmwrite

>> dlmwrite('data.csv',A,',');

参考文献

[1] http://en.wikipedia.org/wiki/Endianness

  1. 机器格式(IE,ieee-beieee-levaxd 等)的二进制数据可以在任一fopen 或 Matlab 中的 fread 命令.支持的详细信息机器格式可以在Matlab 的 fopen 文档.

  1. The machine format (IE, ieee-be, ieee-le, vaxd etc.) of the binary data can be specified in either the fopen or the fread commands in Matlab. Details of the supported machine format can be found in Matlab's documentation of fopen.

Scott French 的评论 比尔的回答建议将数据读入int16 变量.为此,请使用

Scott French's comment to Bill's answer suggests reading the data into an int16 variable. To do this use

>> A = int16(fread(fid,count,precision,machineFormat));

其中 count 是要读取的数据,precision 是数据格式和机器格式是每个字节的编码.

where count is the size/shape of the data to be read, precision is the data format, and machineformat is the encoding of each byte.

查看命令fseek 来移动文件.例如,

See commands fseek to move around the file. For example,

>> fseek(fid,0,'bof');

将文件倒回到bof代表文件开头的开头.

will rewind the file to the beginning where bof stands for beginning of file.

这篇关于在 Matlab 中读取和写入二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆