python中如何基于numpy创建矩阵

python的功能强大依赖于各种库发挥的作用,例如numpy库就提供了矩阵运算的功能,如果我们想要进行矩阵运算,首先要导入numpy的包,创建矩阵。本文介绍python中基于numpy创建矩阵的三种方法:1、手动创建;2、利用numpy数组创建;3、使用numpy.matix()函数创建矩阵。

一、导入numpy

>>>fromnumpyimport*;#导入numpy的库函数
>>>importnumpyasnp;#这个方式使用numpy的函数时,需要以np.开头。

二、python基于numpy创建矩阵方法

1、手动创建

a=np.mat('123;456;789')#中间打逗号也可以b=np.mat('1,2,3;4,5,6;7,8,9')

2、利用numpy数组创建

c=np.mat(np.arange(9))#一维的矩阵
c=np.mat(np.arange(9).reshape(3,3))

3、使用numpy.matix()函数创建矩阵

importnumpyasnp

#create2x2matrix
a=np.matrix([[1,2],[3,4]])#usingarrayofarray
print('2x2matrixis:\n',a)
#usingshapeattributetogetthetupledescribingmatrixshape
print('Thedimensionofthematrixis:',a.shape)
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。