矩阵的Python numpy矩阵

2024-06-16 11:15:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个代码,它是有效的。似乎有更好的方法可以做到这一点。有人知道更清洁的解决方案吗

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()

Tags: inforlennprangepltemptymatrix2
1条回答
网友
1楼 · 发布于 2024-06-16 11:15:05

排列轴并重塑-

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

相关问题 更多 >