Numpy中矩陣和數組的區別

矩陣(Matrix)和數組(Array)的區別主要有如下兩點:數組

  • 矩陣只能爲2維的,而數組能夠是任意維度的。
  • 矩陣和數組在數學運算上會有不一樣的結構。

 

代碼展現dom

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))ui

 
 
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).)spa

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.數組的建立code

  • 經過傳入列表建立
  • 經過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.矩陣和數組的數學運算blog

  • 矩陣的乘法和加法

矩陣的乘法和加法和線性代數的矩陣加法和乘法一致,運算符號也同樣用*,**表示平方,例如e**2 =e*e。ip

  • 數組的加法和乘法

數組的乘法和加法爲相應位置的數據乘法和加法。ci

相關文章
相關標籤/搜索