我对 Python 很陌生。我需要一个 3 维矩阵,以便以某种长度保存 8 x 8 矩阵。我们拨打 530 吧。问题是我使用了 np.array 因为矩阵不能有超过 2 个维度,正如 numpy 所说的那样。
R = zeros([8,8,530],float)
我将 8 x 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'

有帮助吗?

解决方案

如果您输入 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 文件中存储多个对象。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top