python_numpy的矩阵运算及对应的matlab写法

来源:互联网 发布:淘宝简易摄影棚 编辑:程序博客网 时间:2024/06/06 01:15

背景:

NumPy和Matlab不一样,对于多维数组的运算,缺省情况下并不使用矩阵运算,可以调用相应的函数对数组进行矩阵运算。或者使用numpy库提供了的matrix类,用matrix类创建的是矩阵对象,它们的加减乘除运算缺省采用矩阵方式计算,用法和matlab十分类似。不过一般用户很容易将NumPy中同时存在的ndarray和matrix对象弄混,一般不建议在大程序中使用。下面简单介绍python的多维数组怎么进行常用的矩阵运算,以及对应的matlab写法。

代码:

import numpy as np#矩阵乘法print()print("矩阵乘法(Matlab:a*b)")print("==================================")print()a = np.arange(1,5).reshape(2,-1)b = np.arange(0,4).reshape(2,-1)c = np.dot(a,b)print("a = ",a)print("b = ",b)print("c = np.dot(a,b) = ",c)#内积print()print("向量内积(Matlab:sum(a(:).*b(:))或a(:)'*b(:))")print()print("==================================")print()a = a.reshape(-1,)b = b.reshape(-1,)c = np.dot(a,b)print("a = ",a)print("b = ",b)print("c = np.dot(a,b) = ",c)#点乘print()print("点乘:(Matlab:a(:).*b(:)))")print()print("==================================")print()c = a*bprint("a = ",a)print("b = ",b)print("c = a*b = ",c)#inner:转置乘法print()print("inner:(Matlab:a.*b'))")print()print("==================================")a = np.arange(1,5).reshape(2,-1)b = np.arange(0,4).reshape(2,-1)c = np.inner(a,b)print("a = ",a)print("b = ",b)print("c = np.inner(a,b) = ",c)#outer:两个一维向量扩成矩阵print()print("outer:(Matlab:a(:)*b(:)'))")print()print("==================================")a = np.arange(1,5).reshape(2,-1)b = np.arange(0,4).reshape(2,-1)c = np.outer(a,b)print("a = ",a)print("b = ",b)print("c = np.outer(a,b) = ",c)

输出:



矩阵乘法(Matlab:a*b)
==================================


a =  [[1 2]
 [3 4]]
b =  [[0 1]
 [2 3]]
c = np.dot(a,b) =  [[ 4  7]
 [ 8 15]]


向量内积(Matlab:sum(a(:).*b(:))或a(:)'*b(:))


==================================


a =  [1 2 3 4]
b =  [0 1 2 3]
c = np.dot(a,b) =  20


点乘:(Matlab:a(:).*b(:)))


==================================


a =  [1 2 3 4]
b =  [0 1 2 3]
c = a*b =  [ 0  2  6 12]


inner:(Matlab:a.*b'))


==================================
a =  [[1 2]
 [3 4]]
b =  [[0 1]
 [2 3]]
c = np.inner(a,b) =  [[ 2  8]
 [ 4 18]]


outer:(Matlab:a(:)*b(:)'))


==================================
a =  [[1 2]
 [3 4]]
b =  [[0 1]
 [2 3]]
c = np.outer(a,b) =  [[ 0  1  2  3]
 [ 0  2  4  6]
 [ 0  3  6  9]
 [ 0  4  8 12]]