矩阵(Matrix)和数组(Array)的区别主要有以下两点:
矩阵只能为2维的,而数组可以是任意维度的。
矩阵和数组在数学运算上会有不同的结构。
代码展示
1.矩阵的创建
采用mat函数创建矩阵
class numpy.mat(data, dtype=None)
(注释:Unlike matrix, asmatrix does not make a copy if the input is already a matrix or an ndarray. Equivalent to matrix(data, copy=False).这句话的含义也就是说,当传入的参数为一个矩阵或者ndarray的数组时候,返回值是和传入参数相同的引用,也就是当传入参数发生改变时候,返回值也会相应的改变。相当于numpy.matrix(data, copy=False))
import numpy as np
e = np.array([[1, 2], [3, 4]]) # 传入的参数为ndarray时
# e= np.matrix([[1, 2], [3, 4]]) # 传入的参数为矩阵时
print(e)
print('e的类型:', type(e))
print('---'*5)
e1 = np.mat(e)
print(e1)
print('e1的类型:', type(e1))
print('---'*5)
print('改变e中的值,分别打印e和e1')
# 注意矩阵和ndarray修改元素的区别
e[0][0] = 0 # 传入的