Next: Reading and writing vectors Up: numpy_arrays Previous: numpy_arrays

# Vectors and Matrices

Here is code that defines a matrix and a vector and prints the matrix-vector product.

 ``` #! /usr/bin/python3 # Define a vector and a matrix and compute the matrix-vector product import numpy as np # Define an arbitrary vector v = np.array([1,-1,1]) # Define an arbitrary 5 x 3 matrix M = np.array([[1,-2,1],[2,-4,2],[3,-6,3],[4,-8,4],[5,-10,5]]) # Matrix product u = np.dot(M, v) print(u) ```

Here is an explanation of the code:
 ``` import numpy as np ```

This statement gives you access to the numpy package. Numpy functions and objects must then be prefixed with `np`. Without the `as np` you would have to prefix them with `numpy`, which requires more typing.

 ``` v = np.array([1,-1,1]) ```

This statement defines an array (think "vector") with three elements and assigns their values. They can be accessed with a subscript, as in `v[2]`.

 ``` M = np.array([[1,-2,1],[2,-4,2],[3,-6,3],[4,-8,4],[5,-10,5]]) ```

This statement defines an array (think "matrix") with five rows and three columns and assigns their values. Elements of the array can be accessed with either `M[i,j]`. `M[i][j]` also works.

 ``` u = np.dot(M, v) ```

The generalized dot product here results in the matrix product of `M` with `v`, where `v` is interpreted as a column vector. The resulting vector `u` in this case has five elements, because `M` has five rows.

Try running the code to see the result.

Carleton DeTar 2018-02-12