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

3

我目前正在尝试在Matlab中将一个数组保存为二进制文件,发送到Python并在Python中读取它。然而,在运行时,Matlab显示错误。我正在使用以下代码:

在Matlab中读取数组,转换为二进制文件并传递给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

然而,当我运行这个程序时,没有任何内容被打印出来。我猜测二进制文件没有被正确地传递给squared.py文件。谢谢您的反馈。Nazmul

我在if name == 'main'中使用了正确的格式。但是在问题中它没有正确显示。 - Nazmul
在您的Python脚本中,您硬编码了名称“nazmul.bin”,因此不需要传递值。如果尝试在不传递值的情况下运行它会发生什么? - Jeff
1
此外,Matlab 可能没有写入 Python 读取的相同路径。如果是这种情况,您应该在一个或两个脚本中指定路径。 - Jeff
1个回答

4
这里有几个问题。
  1. 检查'main'时应使用双下划线,即 __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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接