python - 使用Python创建三维矩阵结构并写入mat文件

标签 python matrix numpy scipy mat-file

我对 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() 作为字典方法,很明显我们需要使用字典(一组键、值对;google “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 文件中存储多个对象。

关于python - 使用Python创建三维矩阵结构并写入mat文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9448940/

相关文章:

python - 生成四元对

python - 不理解地计算总和

R:值因调用方法而异

python - 在 Mac 或 Linux 上使用 Python 发送电子邮件的最佳方式?

python - wxpython 定时器不工作

python - 在 Caffe 中训练孪生网络

javascript - 了解 SVG 中的矩阵

Python求和麻烦

python - 替换 Pandas Dataframe 中的值

python - 学习 : KNeighborsRegressor vs KNeighborsClassifer