将matlab变量导出为python用法的文本

时间:2011-08-19 06:33:43

标签: python matlab file-io

让我们开始说我是matlab的初学者。我正在使用python,现在我收到了matlab文件中的一些数据,我需要将其导出为可以与python一起使用的格式。

我已经google了一下,发现我可以使用以下方法将matlab变量导出到文本文件中:

dlmwrite('my_text', MyVariable, 'delimiter' , ',');

现在我需要导出的变量是一个16000 x 4000矩阵的0.006747668446927形式的双精度数。现在问题出现在这里。我需要导出每个double的完整值。尝试使用该功能可以让我以0.0067477的格式导出数字。这是行不通的,因为我需要更多的精确度来做我正在做的事情。那么如何导出每个变量的完整值呢?或者如果你有更优雅的方式在python中使用那个巨大的matlab矩阵,请随意。

此致 波格丹

4 个答案:

答案 0 :(得分:6)

在Python和Matlab之间交换大块的数值数据 推荐HDF5

Python绑定称为h5py

以下是两个方向的两个例子。首先来自 Matlab到Python

% matlab
points = [1 2 3 ; 4 5 6 ; 7 8 9 ; 10 11 12 ];
hdf5write('test.h5', '/Points', points);

# python
import h5py
with h5py.File('test.h5', 'r') as f:
    points = f['/Points'].value    

现在从Python到Matlab

# python
import h5py
import numpy
points = numpy.array([ [1., 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ])
with h5py.File('test.h5', 'w') as f:
    f['/Points'] = points

% matlab
points = hdf5read('test.h5', '/Points');

注意 Matlab中的一列将在Python中排成一行,反之亦然。这不是一个错误,而是C和Fortran解释内存中连续数据的方式之间的区别。

答案 1 :(得分:0)

Scipy有本地读取MATLAB .mat文件的工具:参见例如http://www.janeriksolem.net/2009/05/reading-and-writing-mat-files-with.html

答案 2 :(得分:0)

虽然我喜欢基于hdf5的答案,但我仍然认为文本文件和CSV适合较小的东西(你可以在文本编辑器,电子表格中打开它们)。在那种情况下,我会使用MATLABs fopen / fprintf / fclose而不是dlmwrite - 我喜欢把事情弄清楚。然后,这个dlmwrite对于多维数组可能更好。

答案 3 :(得分:0)

你可以简单地将你的变量写成文件作为二进制数据,然后用你想要的任何语言读取它,无论是MATLAB,Python,C等。例如:

MATLAB(写)

X = rand([100 1],'single');

fid = fopen('file.bin', 'wb');
count = fwrite(fid, X, 'single');
fclose(fid);

MATLAB(阅读)

fid = fopen('file.bin', 'rb');
data = fread(fid, Inf, 'single=>single');
fclose(fid);

Python(阅读)

import struct

data = []
f = open("file.bin", "rb")
try:
    # read 4 bytes at a time (float)
    bytes = f.read(4)           # returns a sequence of bytes as a string
    while bytes != "":
        # string byte-sequence to float
        num = struct.unpack('f',bytes)[0]

        # append to list
        data.append(num);

        # read next 4 bytes
        bytes = f.read(4)
finally:
    f.close()

# print list
print data

C(阅读)

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fp = fopen("file.bin", "rb");

    // Determine size of file
    fseek(fp, 0, SEEK_END);
    long int lsize = ftell(fp);
    rewind(fp);

    // Allocate memory, and read file
    float *numbers = (float*) malloc(lsize);
    size_t count = fread(numbers, 1, lsize, fp);
    fclose(fp);

    // print data
    int i;
    int numFloats = lsize / sizeof(float);
    for (i=0; i<numFloats; i+=1) {
        printf("%g\n", numbers[i]);
    }

    return 0;
}