【问题标题】:Pass data between MATLAB R2011b and Python (Windows 7)在 MATLAB R2011b 和 Python (Windows 7) 之间传递数据
【发布时间】:2017-06-10 08:10:21
【问题描述】:

朋友们好,

我想在 MATLAB 和 Python 之间传递数据,一种方法是在 Python 中使用 ma​​tlab.engine 或从 MATLAB 调用 Python 库。但是这种方法需要 MATLAB 2014 版本,不像我的 MATLAB R2011b。

因此,我请求您指导另一种方法,以便在 Python 和 MATLAB R2011b 版本之间进行通信。

提前致谢

【问题讨论】:

    标签: python matlab python-2.7 parameter-passing language-interoperability


    【解决方案1】:

    都支持 二进制文件格式。
    您可以使用hdf5read/hdf5write在matlab中读/写hdf5数据文件:

    >> hdf5write('./data_from_matlab.h5', '/data', x);
    

    在 python 中你有h5py:

    import h5py, numpy as np
    
    with h5py.File('./data_from_matlab.h5', 'r') as R:
        x = np.array(R['data'])
    

    反过来:

    import h5py, numpy as np
    
    with h5py.File('./data_from_python.h5', 'w') as W:
        W.create_dataset(name='data', data=np.zeros((10,10),dtype='f4'))
    

    在 Matlab 中阅读

    >> data = hdf5read('./data_from_python.h5','/data');  % you might need to remove '/' from '/data'...
    

    【讨论】:

    • 感谢 Shai 的快速回复。我试过了,但我只能在 MATLAB 中创建 .h5 文件,但是当尝试在 Ipython 中读取时,我无法...错误是 OSERROR:无法打开文件
    • @Abhishek 文件是否存在?您对创建的文件有读取权限吗?文件是否可能已损坏?如果你输入 shell h5ls <filename> 你会看到什么?
    • 是的,我是在 MATLAB 中创建的,当我输入 cmd 时...它用 { 10, 10} 给出了路径和数据
    • 现在我交叉检查,文件存在于位置但无法在 python 中打开
    • with h5py.File(''(用'/'分隔的完整链接)./data_from_matlab.h5', 'r') as R: x = np.array(R['(完整链接with '/' separator) data']) 但得到 KeyError: 'Unable to open object(Component not found)'
    【解决方案2】:

    根据您想要做什么和您的数据类型,您可以将其写入文件并以其他语言读取。你可以在 python 部分使用numpy.fromfile

    【讨论】:

    • 感谢 UpSampler 的创造性方法。实际上我的数据文件的实际格式是 .dat 。那么如何读取这样的文件,我尝试了 xls 的导入方式,但没有工作,因为文件大小为 350MB
    猜你喜欢
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多