《Python Scripting for Computational Science, Third Edition》由 Hans Petter Langtangen等编写,找到这本书纯粹是为了学怎么用python输入矩阵,比较初级,但是有效。
取自第四章 数字计算。
要像输入矩阵类型的数据必须先导入库,在这里Python的扩展称为数值python,Numpy,所以
from numpy import *
这样我们就可以使用python的数值方法,与matlab类似。
所有的代码段在该文件中
src/py/intro/NumPy_basics.py
1,建立矩阵
例如
>>> from numpy import *
>>> n = 4
>>> a = zeros(n) # one-dim. array of length n
>>> print a # str(a)
[ 0. 0. 0. 0.]
>>> a # repr(a)
array([ 0., 0., 0., 0.])
>>> p = q = 2
>>> a = zeros((p,q,3)) # p*q*3 three-dim. array
>>> print a
[[[ 0. 0. 0.]
[ 0. 0. 0.]]
[[ 0. 0. 0.]
[ 0. 0. 0.]]]
r = x.copy()
也可以以x的模式建立矩阵
r = zeros(x.shape, x.dtype)
>>> x = linspace(-5, 5, 11)
>>> print x
[-5. -4. -3. -2. -1. 0. 1. 2. 3. 4. 5.]
也可以用 r_[start,stop,incj]形式
>>> a = r_[-5:5:11j] # same as linspace(-1, 1, 11)
>>> print a
[-5. -4. -3. -2. -1. 0. 1. 2. 3. 4. 5.]
>>> x = arange(-5, 5, 1, float)
>>> print x
[-5. -4. -3. -2. -1. 0. 1. 2. 3. 4.]
>>> x = seq(-5, 5, 1)
>>> print x
[-5. -4. -3. -2. -1. 0. 1. 2. 3. 4. 5.]
4,矩阵的坐标
通常采用以下表示方法
a = linspace(-1, 1, 6)
a[2:4] = -1 # set a[2] and a[3] equal to -1
a[-1] = a[0] # set last element equal to first one
a[:] = 0 # set all elements of a equal to 0
a.fill(0) # set all elements of a equal to 0
for i in xrange(a.shape[0]):
for j in xrange(a.shape[1]):
a[i,j] = (i+1)*(j+1)*(j+2)
print ’a[%d,%d]=%g ’ % (i,j,a[i,j]),
print # newline after each row
>>> import time # module for measuring CPU time
>>> a = linspace(0, 1, 1E+07) # create some array
>>> t0 = time.clock()
>>> b = 3*a -1
>>> t1 = time.clock() # t1-t0 is the CPU time of 3*a-1
>>> for i in xrange(a.size): b[i] = 3*a[i] - 1
>>> t2 = time.clock()
>>> print ’3*a-1: %g sec, loop: %g sec’ % (t1-t0, t2-t1)
3*a-1: 2.09 sec, loop: 31.27 sec