Matlab到Python转换二进制文件读取 [英] Matlab to Python Conversion binary file read
问题描述
我是Matlab和Python的新手,我必须将Matlab中的程序转换为Python.我不确定在Python中从文件读取后如何转换数据.使用的文件是二进制文件.
I am new to both Matlab and Python and I have to convert a program in Matlab to Python. I am not sure how to typecast the data after reading from the file in Python. The file used is a binary file.
下面是Matlab代码:
Below is the Matlab code:
fid = fopen (filename, 'r');
fseek (fid, 0, -1);
meta = zeros (n, 9, 'single');
v = zeros (n, 128, 'single');
d = 0;
for i = 1:n
meta(i,:) = fread (fid, 9, 'float');
d = fread (fid, 1, 'int');
v(i,:) = fread (fid, d, 'uint8=>single');
end
我已经用python编写了以下程序:
I have written the below program in python:
fid = open(filename, 'r')
fid.seek(0 , 0)
meta = np.zeros((n,9),dtype = np.float32)
v = np.zeros((n,128),dtype = np.float32)
for i in range(n):
data_str = fid.read(9);
meta[1,:] = unpack('f', data_str)
对于此解包,我得到的错误为
For this unpack, I getting the error as
解压缩需要长度为4的字符串参数"
"unpack requires a string argument of length 4"
. 请提出建议以使其正常工作.
. Please suggest someway to make it work.
推荐答案
我在这个问题上看了一些,主要是因为在不久的将来我也需要这个.事实证明,有一个使用numpy的非常简单的解决方案,假设您像我一样存储了一个matlab矩阵.
I looked a little in the problem mainly because I need this in the near future, too. Turns out there is a very simple solution using numpy, assuming you have a matlab matrix stored like I do.
import numpy as np
def read_matrix(file_name):
return np.fromfile(file_name, dtype='<f') # little-endian single precision float
arr = read_matrix(file_path)
print arr[0:10] #sample data
print len(arr) # number of elements
您必须了解自己的数据类型(dtype).有关帮助,请此处.我使用fwrite(fid,value,'single');
将数据存储在matlab中,如果您有相同的数据,则上面的代码将起作用.
注意,返回的变量是一个列表.您必须将其格式化以匹配数据的原始形状,在我的情况下,len(arr)来自大小为15360 x 20的矩阵为307200.
The data type (dtype) you must find out yourself. Help on this is here. I used fwrite(fid,value,'single');
to store the data in matlab, if you have the same, the code above will work.
Note, that the returned variable is a list; you'll have to format it to match the original shape of your data, in my case len(arr) is 307200 from a matrix of the size 15360 x 20.
这篇关于Matlab到Python转换二进制文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!