python_numpy的矩阵运算及对应的matlab写法
2017-09-24 08:46
453 查看
背景:
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包---矩阵运算
- Python知识(6)--numpy做矩阵运算
- python中的矩阵运算numpy
- Python numpy(ndarray 随机数组 常用操作 线性方程组和矩阵运算)
- Python 机器学习——线性代数和矩阵运算:从matlab迁移到python
- [转]numpy线性代数基础 - Python和MATLAB矩阵处理的不同
- numpy线性代数基础 - Python和MATLAB矩阵处理的不同
- Python矩阵运算库numpy常用函数
- python中numpy与matlab的对应关系
- Python第三方矩阵库numpy矩阵基本运算
- python中numpy与matlab的对应关系
- Python中的numpy矩阵运算
- Python 与 Matlab 矩阵操作对应表
- Python—numpy做矩阵运算
- numpy线性代数基础 - Python和MATLAB矩阵处理的不同
- python 的矩阵运算——numpy
- 【python学习笔记】18:numpy数组函数与矩阵运算
- MATLAB矩阵的基本运算及操作
- [Python]使用Numpy对矩阵进行转置