在Matlab中保存数组为二进制文件,传递给Python并在Python中读取该文件

3 投票
1 回答
759 浏览
提问于 2025-04-16 19:21

我现在正在尝试在Matlab中保存一个数组为二进制文件(bin文件),然后把它发送到Python中读取。不过,当我运行的时候,Matlab出现了错误。我使用了以下代码:

在Matlab中读取数组,转换为bin文件并传递给Python:

array1 = rand(5,1); %% array1 is the desired array that needs to be sent to Python

fid = fopen('nazmul.bin','wb'); %% I want to save array1 in the nazmul.bin file

fwrite(fid,array1);

status=fclose(fid);

python('squared.py','nazmul.bin'); %% I want to send the parameters to squared.py program

squared.py文件:

import sys

if __name__ == '__main__':
f = open("nazmul.bin", "rb")   # Trying to open the bin file

try:

   byte = f.read(1)       # Reading the bin file and saving it in the byte array

   while byte != "":

   # Do stuff with byte.

       byte = f.read(1)

   finally:

       f.close()

   print byte                # printing the byte array from Python

但是,当我运行这个程序时,什么都没有打印出来。我猜测这个bin文件没有正确传递给squared.py文件。

谢谢你的反馈。

Nazmul

1 个回答

4

这里有几个问题。

  1. 检查'主程序'时,你应该用双下划线。也就是说,应该写成 __main__ == "__main__"
  2. 你并不是在收集字节,而是总是只存储最后一个读取的字节。因此,最后一个字节总是 ""
  3. 最后,看起来缩进不太对。我猜这只是StackOverflow格式的问题。
  4. 还有一个潜在的问题 - 当你在MATLAB中使用fwrite(fid, A)时,它会假设你想写入字节(8位数字)。但是,你的 rand() 命令生成的是实数,所以MATLAB会先把结果四舍五入成整数,这样你的二进制文件里只会有'0'或'1'。

最后一点:一次读取一个字节可能效率很低。更好的方法是一次读取大块数据,或者如果文件很小,可以一次性用 read() 操作读取整个文件。

修正后的Python代码如下:

if __name__ == '__main__':
   f = open("xxx.bin", "rb")   # Trying to open the bin file

   try:
     a = [];
     byte = f.read(1)       # Reading the bin file and saving it in the byte array
     while byte != "":
       a.append(byte);
       # Do stuff with byte.
       byte = f.read(1)

   finally:
       f.close()

   print a;

撰写回答