Page - 52 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 52 -
Text of the Page - 52 -
52 2 AFewMoreSteps
When copying a slice, the same logic applies as when copying the whole array. To
demonstrate theproblem,wecontinue thedialogueas
In [6]: y[0] = -1.0
In [7]: y
Out[7]: array([-1., 13., 14., 15.]) # ...changed
In [8]: x
Out[8]: array([ 11., -1., 13., 14., 15., 16.]) # ...changed
As for the whole array, the function copy may be used (after importing: from
numpy import copy)asy = copy(x[1:5]) togivea“real”copy.
2.3.6 Two-DimensionalArraysandMatrixComputations
For readers who are into linear algebra, it might be useful to see how matrices and
vectors may be handled with NumPy arrays.13 Above, we saw arrays where the
individual elements could be addressed with a single index only. Such arrays are
oftencalledvectors.
To calculate with matrices, we need arrays with more than one “dimension”.
Such arrays may be generated in different ways, for example by use of the same
zerosfunctionthatwehaveseenbefore, it justhas tobecalledabitdifferently.Let
usillustratebydoingasimplematrix-vectormultiplicationwith thenumpyfunction
dot:
In [1]: import numpy as np
In [2]: I = np.zeros((3, 3)) # create matrix (note parentheses!)
In [3]: I
Out[3]:
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
In [4]: type(I) # confirm that type is ndarray
Out[4]: numpy.ndarray
In [5]: I[0, 0] = 1.0; I[1, 1] = 1.0; I[2, 2] = 1.0 # identity matrix
In [6]: x = np.array([1.0, 2.0, 3.0]) # create vector
In [7]: y = np.dot(I, x) # computes matrix-vector product
In [8]: y
Out[8]: array([ 1., 2., 3.])
13 If you are not familiar with matrices and vectors, and such calculations are not on your
agenda, you should consider skipping (or at least wait with) this section, as it is not required for
understanding the remaining parts of the book.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik