mik*_*keP 10 python matlab structure preserve mat-file
我有一个我使用的mat文件
from scipy import io
mat = io.loadmat('example.mat')
Run Code Online (Sandbox Code Playgroud)
从matlab开始,example.mat包含以下结构
>> load example.mat
>> data1
data1 =
LAT: [53x1 double]
LON: [53x1 double]
TIME: [53x1 double]
units: {3x1 cell}
>> data2
data2 =
LAT: [100x1 double]
LON: [100x1 double]
TIME: [100x1 double]
units: {3x1 cell}
Run Code Online (Sandbox Code Playgroud)
在matlab中,我可以像data2.LON一样轻松访问数据.它在python中并不是那么简单.虽然喜欢它,但它给了我几个选项
mat.clear mat.get mat.iteritems mat.keys mat.setdefault mat.viewitems
mat.copy mat.has_key mat.iterkeys mat.pop mat.update mat.viewkeys
mat.fromkeys mat.items mat.itervalues mat.popitem mat.values mat.viewvalues
Run Code Online (Sandbox Code Playgroud)
有可能在python中保留相同的结构吗?如果没有,如何最好地访问数据?我正在使用的当前python代码非常难以使用.
谢谢
mik*_*keP 12
找到关于matlab struct和python的本教程
http://docs.scipy.org/doc/scipy/reference/tutorial/io.html
当我需要从 MATLAB 将存储在结构数组 {strut_1,struct_2} 中的数据加载到 Python 中时,我从使用 .strut 加载的对象中提取键和值的列表 scipy.io.loadmat。然后我可以将它们组装到自己的变量中,或者如果需要,将它们重新打包到字典中。该exec命令的使用可能并不适合所有情况,但如果您只是尝试处理数据,它就可以很好地工作。
# Load the data into Python
D= sio.loadmat('data.mat')
# build a list of keys and values for each entry in the structure
vals = D['results'][0,0] #<-- set the array you want to access.
keys = D['results'][0,0].dtype.descr
# Assemble the keys and values into variables with the same name as that used in MATLAB
for i in range(len(keys)):
key = keys[i][0]
val = np.squeeze(vals[key][0][0]) # squeeze is used to covert matlat (1,n) arrays into numpy (1,) arrays.
exec(key + '=val')
Run Code Online (Sandbox Code Playgroud)