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]])
05-06 02:28