📅  最后修改于: 2023-12-03 15:04:20.526000             🧑  作者: Mango
The matrix.reshape()
function in the numpy library is used to reshape an array, including matrices, in a desired shape.
numpy.matrix.reshape(shape, order='C')
shape
: The new shape that the matrix should be reshaped into. This can be specified as a tuple of integers or an integer representing the new shape of the array. It should be compatible with the original shape.
order
(optional): This parameter determines the order the elements are read from the original matrix during reshaping. It can be one of the following values:
'C'
(default): C-style order, which means elements are read row-wise.'F'
: Fortran-style order, which means elements are read column-wise.'A'
: If any memory order is acceptable, this value can be used. It uses 'C'
order if the array is contiguous in memory, and 'F'
order otherwise.A reshaped matrix with the specified shape.
import numpy as np
matrix = np.matrix([[1, 2, 3], [4, 5, 6]])
resized_matrix = matrix.reshape((3, 2))
print(resized_matrix)
Output:
[[1 2]
[3 4]
[5 6]]
The above example demonstrates how to reshape a matrix using the matrix.reshape()
function. In this case, the original matrix is reshaped into a 3x2 matrix. The resulting matrix is printed, showing the new shape.
Note that the reshaping is done row-wise by default. If you want to reshape the matrix column-wise, you can specify the order parameter as 'F'
.
import numpy as np
matrix = np.matrix([[1, 2, 3], [4, 5, 6]])
resized_matrix = matrix.reshape((3, 2), order='F')
print(resized_matrix)
Output:
[[1 4]
[2 5]
[3 6]]
Here, the matrix is reshaped into a 3x2 matrix using Fortran-style order. The resulting matrix is printed, showing the new shape in a column-wise fashion.
By utilizing the matrix.reshape()
function, you can easily reshape numpy arrays, including matrices, to match your desired dimensions or order.