矩陣(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) print(n) o = np.linspace(0, 4, 9) o.resize(3, 3) 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。
- 數組的加法和乘法
數組的乘法和加法為相應位置的數據乘法和加法。
