簡體   English   中英

矩陣的Python numpy矩陣

[英]Python numpy matrix of matrix

我有這個代碼,它有效。 似乎有更好的方法可以做到這一點。 有誰知道更清潔的解決方案?

def Matrix2toMatrix(Matrix2):
    scaleSize = len(Matrix2[0, 0])

    FinalMatrix = np.empty([len(Matrix2)*scaleSize, len(Matrix2[0])*scaleSize])
    for x in range(0, len(Matrix2)):
        for y in range(0, len(Matrix2[0])):
            for xFinal in range(0, scaleSize):
                for yFinal in range(0, scaleSize):
                    FinalMatrix[(x*scaleSize)+xFinal, (y*scaleSize)+yFinal] = Matrix2[x, y][xFinal, yFinal]
    return FinalMatrix

這是 Matrix2 是一個 4x4 矩陣的地方,每個單元格包含一個 2x2 矩陣


完整代碼,以防有人想知道:

import matplotlib.pyplot as plt
import numpy as np
    

def Matrix2toMatrix(Matrix2):
    scaleSize = len(Matrix2[0, 0])

    FinalMatrix = np.empty([len(Matrix2)*scaleSize, len(Matrix2[0])*scaleSize])
    for x in range(0, len(Matrix2)):
        for y in range(0, len(Matrix2[0])):
            for xFinal in range(0, scaleSize):
                for yFinal in range(0, scaleSize):
                    FinalMatrix[(x*scaleSize)+xFinal, (y*scaleSize)+yFinal] = Matrix2[x, y][xFinal, yFinal]
    return FinalMatrix


XSize = 4
Xtest = np.array([[255, 255, 255, 255]
                 ,[255, 255, 255, 255]
                 ,[127, 127, 127, 127]
                 ,[0, 0, 0, 0]
                  ])

scaleFactor = 2

XMarixOfMatrix = np.empty([XSize, XSize], dtype=object)
Xexpanded = np.empty([XSize*scaleFactor, XSize*scaleFactor], dtype=int)  # careful, will contain garbage data

for xOrg in range(0, XSize):
    for yOrg in range(0, XSize):

        newMatrix = np.empty([scaleFactor, scaleFactor], dtype=int)  # careful, will contain garbage data

        # grab org point equivalent
        pointValue = Xtest[xOrg, yOrg]

        newMatrix.fill(pointValue)

        # now write the data
        XMarixOfMatrix[xOrg, yOrg] = newMatrix


# need to concat all matrix together to form a larger singular matrix
Xexpanded = Matrix2toMatrix(XMarixOfMatrix)

img = plt.imshow(Xexpanded)
img.set_cmap('gray')
plt.axis('off')
plt.show()

置換軸和重塑 -

m,n = Matrix2.shape[0], Matrix2.shape[2]
out = Matrix2.swapaxes(1,2).reshape(m*n,-1)

對於置換軸,我們也可以使用np.transposenp.rollaxis ,因為在功能上都是相同的。

使用示例運行進行驗證 -

In [17]: Matrix2 = np.random.rand(3,3,3,3)

# With given solution
In [18]: out1 = Matrix2toMatrix(Matrix2)

In [19]: m,n = Matrix2.shape[0], Matrix2.shape[2]
    ...: out2 = Matrix2.swapaxes(1,2).reshape(m*n,-1)

In [20]: np.allclose(out1, out2)
Out[20]: True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM