52
2 A Few More Steps
When copying a slice, the same logic applies as when copying the whole array. To
demonstrate the problem, we continue the dialogue as
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) as y = copy(x[1:5]) to give a “real” copy.
2.3.6 Two-Dimensional Arrays and Matrix Computations
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
often called vectors.
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
zeros function that we have seen before, it just has to be called a bit differently. Let
us illustrate by doing a simple matrix-vector multiplication with the numpy function
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.
Précédent

- 74/350

Suivant