Numpy中矩阵和数组的区别
矩阵(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  # 传⼊的参数为ndarray时
# e[0, 0] = 0  # 传⼊的参数为矩阵时
print(e)
print(e1)
print('---'*5)
[[1 2]
[3 4]]
e的类型: <class'numpy.matrix'>
---------------
[[1 2]
[3 4]]
e1的类型: <class'numpy.matrix'>
---------------
改变e中的值,分别打印e和e1
[[0 2]
[3 4]]
[[0 2]
[3 4]]
---------------
采⽤matrix函数创建矩阵
class numpy.matrix(data, dtype=None, copy=True)
(注释:Returns a matrix from an array-like object, or from a string of data. A matrix is a specialized 2-D array that retains its 2-D nature through operations. It has certain special operators, such as * (matrix multiplication) and ** (matrix power).)
import numpy as np
e = np.array([[1, 2], [3, 4]])
# e = '1 2;3 4'  # 通过字符串创建矩阵
e1 = np.matrix(e)  # 传⼊的参数为矩阵时
print(e1)
print('e1的类型:', type(e1))
print('---'*5)
print('改变e中的值,分别打印e和e1')
e[0][0] = 0
print(e)
print(e1)
print('---'*5)
[[1 2]
[3 4]]
e1的类型: <class'numpy.matrix'>
---------------
改变e中的值,分别打印e和e1
[[0 2]
[3 4]]
[[1 2]
[3 4]]
---------------
2.数组的创建
通过传⼊列表创建
通过range()和reshape()创建
linspace()和reshape()创建
通过内置的⼀些函数创建
import numpy as np
e = [[1, 2], [3, 4]]
e1 = np.array(e)
print(e)
n = np.arange(0, 30, 2)  # 从0开始到30(不包括30),步长为2
n = n.reshape(3, 5)
numpy教程 pdfprint(n)
o = np.linspace(0, 4, 9)
print(o)
a = np.ones((3, 2))
print(a)
b = np.zeros((2, 3))
print(b)
c = np.eye(3)  # 3维单位矩阵
print(c)
y = np.array([4, 5, 6])
d = np.diag(y)  # 以y为主对⾓线创建矩阵
print(d)
e = np.random.randint(0, 10, (4, 3))
print(e)
---------------
[[1, 2], [3, 4]]
[[ 0  2  4  6  8]
[10 12 14 16 18]
[20 22 24 26 28]]
[[0.  0.5 1. ]
[1.5 2.  2.5]
[3.  3.5 4. ]]
[[1. 1.]
[1. 1.]
[1. 1.]]
[[0. 0. 0.]
[0. 0. 0.]]
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[[4 0 0]
[0 5 0]
[0 0 6]]
[[3 0 2]
[1 5 1]
[9 4 7]
[5 8 9]]
3.矩阵和数组的数学运算
矩阵的乘法和加法
矩阵的乘法和加法和线性代数的矩阵加法和乘法⼀致,运算符号也⼀样⽤*,**表⽰平⽅,例如e**2 =e*e。
数组的加法和乘法
数组的乘法和加法为相应位置的数据乘法和加法。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。