MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   在Matlab中读写二进制文件 (https://www.labfans.com/bbs/showthread.php?t=22554)

poster 2019-12-07 23:17

在Matlab中读写二进制文件
 
我对matlab的了解只是在需要了解的基础上,因此这可能是一个基本问题。尽管如此,它来了:

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

回答:
正如[URL="https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819"]蜥蜴人Bill[/URL]所写,您可以使用fread将数据加载到向量中。我只想扩大他的答案。

[B]读取数据[/B]

>> fid=fopen('data.bin','rb') % opens the file for reading >> A = fread(fid, count, 'int16') % reads _count_ elements and stores them in A. 命令[I]fopen[/I]和[I]fread[/I]缺省为整数的Little-endian [1]编码。如果您的文件是Big-endian编码的,则需要将[I]fread[/I]更改为

>> A = fread(fid, count, 'int16', 'ieee-be'); 另外,如果您想读取整个文件集

>> count=inf; 如果您想将数据读入[I]n[/I]列矩阵

>> count=[n inf]; [B]写数据[/B]

至于将数据写入文件。 [URL="https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819"]Bill的[/URL]答案中的命令[I]fwrite[/I]将写入二进制文件。如果要将数据写入文本文件,可以使用[I]dlmwrite[/I]

>> dlmwrite('data.csv',A,','); [B]参考文献[/B]

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

[B]更新资料[/B]
[LIST=1][*]可以在Matlab的[I]fopen[/I]或[I]fread[/I]命令中指定二进制数据的机器格式(即[I]ieee-be[/I] , [I]ieee-le[/I] , [I]vaxd[/I]等)。可以在Matlab的[I]fopen[/I]文档中找到支持的机器格式的详细信息。
[*] [URL="https://stackoverflow.com/users/4928/scott-french"]Scott French[/URL]对[URL="https://stackoverflow.com/questions/205735/read-and-write-fromto-a-binary-file-in-matlab#205819"]Bill的回答[/URL] [URL="https://stackoverflow.com/users/4928/scott-french"]的[/URL]评论建议将数据读入int16变量。为此使用

>> A = int16(fread(fid,count,precision,machineFormat)); 其中[I]count[/I]是要读取的数据的大小/形状, [I]precision[/I]是数据格式,而[I]Machineformat[/I]是每个字节的编码。
[*]请参阅命令[I]fseek[/I]来移动文件。例如,

>> fseek(fid,0,'bof'); 会将文件倒带到[I]bof[/I]代表[I]文件开头的开头[/I] 。
[/LIST]


所有时间均为北京时间。现在的时间是 23:17

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.