1. 程式人生 > >python numpy array 與matrix 乘方

python numpy array 與matrix 乘方

extern res resp string ges .com number targe ews

python numpy array 與matrix 乘方

編程語言 waitig 1年前 (2017-04-18) 1272℃ 百度已收錄 0評論

數組array 的乘方(**為乘方運算符)是每個元素的乘方,而矩陣matrix的乘方遵循矩陣相乘,因此必須是方陣。

2*3的數組與矩陣

>>> from numpy import *
>>> import operator
>>> a = array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> m = mat(a)
>>> m
matrix([[1, 2, 3],
        [4, 5, 6]])
>>> a ** 2
array([[ 1,  4,  9],
       [16, 25, 36]])
>>> m ** 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\anaconda\lib\site-packages\numpy\matrixlib\defmatrix.py", line 356, in __pow__
    return matrix_power(self, other)
  File "D:\anaconda\lib\site-packages\numpy\matrixlib\defmatrix.py", line 173, in matrix_power
    raise ValueError("input must be a square array")
ValueError: input must be a square array
>>> 

(mat()函數把array轉化為matrix)

3*3的數組與矩陣

>>> A = array([[1,2,3],[4,5,6],[7,8,9]])
>>> A
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> M = mat(A)
>>> M
matrix([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])
>>> A ** 2
array([[ 1,  4,  9],
       [16, 25, 36],
       [49, 64, 81]])
>>> M ** 2
matrix([[ 30,  36,  42],
        [ 66,  81,  96],
        [102, 126, 150]])

python numpy array 與matrix 乘方