matrix()
方法用于从二维类数组对象创建矩阵。
示例
import numpy as np
# create 2-D array
array1 = [[1, 2], [3, 4]]
# use of matrix() to create matrix
result = np.matrix(array1)
print(result)
'''
Output:
[[1 2]
[3 4]]
'''
matrix() 语法
matrix()
的语法是
numpy.matrix(data, dtype=None, copy=True)
matrix() 参数
matrix()
方法接受以下参数
data
- 用于创建矩阵的输入数据dtype
(可选) - 矩阵的数据类型copy
(可选) - 确定是否应复制data
matrix()返回值
matrix()
方法从类数组对象返回一个矩阵对象。
示例 1:创建矩阵
import numpy as np
# create a list
array1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# use matrix() to create a matrix
result = np.matrix(array1, dtype = int)
print(result)
输出
[[1 2 3] [4 5 6] [7 8 9]]
如果未指定,则默认 dtype
为 float
。
示例 2:matrix() 中 copy 参数的用法
import numpy as np
# create a 2-D array
array1 = [[1, 2], [3, 4]]
# create matrix with default copy=True
matrix1 = np.matrix(array1)
# modify the original data
array1[0][0] = 5
# create matrix with copy=False
matrix2 = np.matrix(array1, copy=False)
print("Matrix with copy=True:")
print(matrix1)
print("Matrix with copy=False:")
print(matrix2)
输出
Matrix with copy=True: [[1 2] [3 4]] Matrix with copy=False: [[5 2] [3 4]]
在上面的示例中,当使用 copy=True
的 matrix()
创建矩阵时,会复制数据,从而生成一个单独的矩阵。
当 copy=False
时,矩阵与原始对象共享数据。修改原始数据会影响矩阵。