Python 将外矩阵旋转n步
我有一个矩阵Python 将外矩阵旋转n步,python,python-2.7,python-3.x,matrix,Python,Python 2.7,Python 3.x,Matrix,我有一个矩阵 matrix1 = [1,2 3,4] matrix2 =[1,2,3 4,5,6 7,8,9] 我想把这个矩阵旋转一步,比如r=1,那么输出就会是 output_matrix = [3,1 4,2] output_matrix = [4,1,2 7,5,3 8,9,6] 我如何才能做到这一点,旋转的步骤将是动态的
matrix1 = [1,2
3,4]
matrix2 =[1,2,3
4,5,6
7,8,9]
我想把这个矩阵旋转一步,比如r=1,那么输出就会是
output_matrix = [3,1
4,2]
output_matrix = [4,1,2
7,5,3
8,9,6]
我如何才能做到这一点,旋转的步骤将是动态的
我找到了这个解决方案,但这是针对固定旋转的,即步骤=1
def rotateMatrix(mat):
if not len(mat):
return
top = 0
bottom = len(mat)-1
left = 0
right = len(mat[0])-1
while left < right and top < bottom:
# Store the first element of next row,
# this element will replace first element of
# current row
prev = mat[top+1][left]
# Move elements of top row one step right
for i in range(left, right+1):
curr = mat[top][i]
mat[top][i] = prev
prev = curr
top += 1
# Move elements of rightmost column one step downwards
for i in range(top, bottom+1):
curr = mat[i][right]
mat[i][right] = prev
prev = curr
right -= 1
# Move elements of bottom row one step left
for i in range(right, left-1, -1):
curr = mat[bottom][i]
mat[bottom][i] = prev
prev = curr
bottom -= 1
# Move elements of leftmost column one step upwards
for i in range(bottom, top-1, -1):
curr = mat[i][left]
mat[i][left] = prev
prev = curr
left += 1
return mat
matrix =[[1,2,3],[4,5,6], [7,8,9]]
matrix = rotateMatrix(matrix)
# # Print modified matrix
print(matrix)
你可以结合旋转和转置来得到你想要的
import numpy as np
m = np.array([[1,2],[3,4]], int)
m1 = np.rot90(m)
m2 = m1.transpose()
print (m2)
这会给你
[[2 1]
[4 3]]
随心所欲地改变
实际上你可以选择这样的元素
import numpy as np
m = np.array([[1,2],[3,4]], int)
# create tuple
new = (m[0][1],m[1][0])
# print list
print (list(new))
[2, 3]
这就是我将如何实施它,但我认为仍有一些改进的余地。支持负r。希望这有帮助。为什么不多次调用旋转矩阵来实现您想要的结果呢?我可以,但这不是一个通用的解决方案。我们不能不使用任何包来实现它,我正在寻找不使用任何库的解决方案。您真的得到了他们的矩阵2示例正确吗?我对此表示怀疑。Stefan Pochmann是正确的。该解决方案不适用于3*3矩阵。是的,Steven是正确的,但举例来说,SVD可以在他的情况下提供帮助。他提到他不需要任何软件包。
def rotate(r,matrix):
'''for rotating the values on the outer ring of a matrix of size HxW'''
height = len(matrix)
width = len(matrix[0])
matrixMap = mapMatrix(height,width)
r %= len(matrixMap)
rotatedMap = matrixMap[-r:]+matrixMap[:-r]
newMatrix = {el:matrix[el[0]][el[1]] for el in matrixMap}
for i,el in enumerate(rotatedMap):
matrix[matrixMap[i][0]][matrixMap[i][1]] = newMatrix[el]
return matrix
def mapMatrix(h,w):
matrix = []
for i in range(w):
matrix.append((0,i))
for i in range(1,h):
matrix.append((i,w-1))
for i in range(w-2,-1,-1):
matrix.append((h-1,i))
for i in range(h-2,0,-1):
matrix.append((i,0))
return matrix