1

我对 Python 很陌生。我需要一个 3 维矩阵,以便以一定长度保存 8 x 8 矩阵。让我们拨打 530。问题是我使用了 np.array,因为 numpy 认为矩阵不能超过 2 维。
R = zeros([8,8,530],float)
我将我的 8 x 8 矩阵计算为 np.matrix
R[:,:,ii] = smallR
然后我尝试将其保存在 mat 文件中,因为 scipy 声称这样做。
sio.savemat('R.mat',R)
但是,错误说“numpy.ndarray”对象没有属性“项目”

/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'

4

1 回答 1

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 文件中。

于 2012-02-25T23:21:53.113 回答