Matrix multiplication
Two
arrays can be manipulated in the usual linear-algebra way using
numpy.matrxmultiply. Here is an example:
>>> import numpy as N >>> import numpy.random >>> A = numpy.random.rand(5, 5) >>> x = numpy.random.rand(5) >>> b = N.dot(A, x) >>> A array([[ 0.78447957, 0.38316272, 0.31135453, 0.70738504, 0.07551859], [ 0.43140155, 0.55929425, 0.28448864, 0.38397626, 0.14849022], [ 0.88869344, 0.93048982, 0.70973804, 0.04341364, 0.27067106], [ 0.95290594, 0.17021306, 0.98377969, 0.73476449, 0.40728296], [ 0.05918968, 0.357716 , 0.33474359, 0.99625301, 0.68345456]]) >>> x array([ 0.47874927, 0.52254844, 0.53053969, 0.07469784, 0.67971556]) >>> b array([ 0.84514734, 0.77933734, 1.47545378, 1.39880365, 0.93182836])
Solving systems of linear equations
To
solve a system of equations Ax=b that is given in matrix form, we can use the
linear algebra package of numpy:
>>> import numpy.linalg as LA >>> x = LA.solve(A,b) >>> x array([ 0.47874927, 0.52254844, 0.53053969, 0.07469784, 0.67971556])
Computing Eigenvectors and Eigenvalues
Here is a small example that computes the Eigenvectors
and Eigenvalues (eig) of the unity matrix.
>>> import numpy >>> import numpy.linalg as LA >>> A = numpy.eye(3) >>> print A [[ 1. 0. 0.] [ 0. 1. 0.] [ 0. 0. 1.]] >>> evalues, evectors = LA.eig(A) >>> print(evalues) [ 1. 1. 1.] >>> print(evectors) [[ 1. 0. 0.] [ 0. 1. 0.] [ 0. 0. 1.]]
Curve fitting of polynomials
Here
is a small example that computes the [trivial] Eigenvectors and Eigenvalues
(eig) of the unity matrix (eye)):
>>> import numpy >>> xdata = numpy.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) >>> ydata = numpy.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) >>> z = numpy.polyfit(xdata, ydata, 3) >>> print z [ 0.08703704 -0.81349206 1.69312169 -0.03968254] >>> p = numpy.poly1d(z) >>> xs = [0.1 * i for i in range(50)] >>> ys = [p(x) for x in xs] >>> import pylab >>> pylab.plot(xdata, ydata, 'o', label = 'data') [] >>> pylab.plot(xs, ys, label='fitted curve') [ ] >>> pylab.ylabel('y') >>> pylab.ylabel('x') >>> pylab.savefig('polyfit.pdf') >>> pylab.show()
Nema komentara:
Objavi komentar