创建一个三维矩阵结构并用Python编写mat文件

时间:2012-02-25 23:09:04

标签: python matrix numpy scipy mat-file

我是Python的新手。我需要一个3维矩阵,以便在一定长度内节省8乘8矩阵。让我们调用530.问题是我使用了np.array,因为矩阵不能超过2维,因为numpy争论。
R = zeros([8,8,530],float)
我计算了我的8乘8矩阵作为np.matrix
R[:,:,ii] = smallR
然后,我尝试将其保存在mat文件中,因为scipy声称这样做 sio.savemat('R.mat',R)
但是,错误说'numpy.ndarray'对象没有属性'items'

/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio.py:266: FutureWarning: Using oned_as default value ('column') This will change to 'row' in future versions oned_as=oned_as)
Traceback (most recent call last):
  File "ClassName.py", line 83, in <module> print (buildR()[1])
  File "ClassName.py", line 81, in buildR sio.savemat('R.mat',R)
 File "/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio.py", line 269, in savemat MW.put_variables(mdict)
  File "/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio5.py", line 827, in put_variables
  for name, var in mdict.items(): AttributeError: 'numpy.ndarray' object has no attribute 'items'

1 个答案:

答案 0 :(得分:3)

如果您输入help(sio.savemat),则会看到:

savemat(file_name, mdict, appendmat=True, format='5', long_field_names=False, do_compression=False, oned_as=None)
    Save a dictionary of names and arrays into a MATLAB-style .mat file.
[...]
    mdict : dict
        Dictionary from which to save matfile variables.

所以即使你不认识.items()作为字典方法,很明显我们需要使用字典(一组键,值对;谷歌“python字典教程”如果必要)。

在这种情况下:

>>> from numpy import zeros
>>> from scipy import io as sio
>>> 
>>> R = zeros([8,8,530],float)
>>> R += 12.3
>>> 
>>> sio.savemat('R.mat', {'R': R})
>>> 
>>> S = sio.loadmat('R.mat')
>>> S
{'R': array([[[ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3],
        [ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3],
        [ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3],
        ..., 

        ..., 
        [ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3],
        [ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3],
        [ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3]]]), '__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file Platform: posix, Created on: Sat Feb 25 18:16:02 2012', '__globals__': []}
>>> S['R']
array([[[ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3],
        [ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3],
        [ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3],
        ..., 

        ..., 
        [ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3],
        [ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3],
        [ 12.3,  12.3,  12.3, ...,  12.3,  12.3,  12.3]]])

基本上,使用字典以便可以命名数组,因为您可以在一个.mat文件中存储多个对象。