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

背景:

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*b

print("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]]

你可能感兴趣的:(python_numpy)