First make sure to import numpy

import numpy as np

Exercises

1) create a linearly spaced array starting at 0, ending at 3, with 30 elements

[Show Solution]

x = np.linspace(0.0, 3.0, 30)

2) create an array of all threes (length 10)

[Show Solution]

x = 3 * np.ones(10)

3) create the following matrix as a 2d array

\[\begin{bmatrix} 4 & 6 & 6 & 9\\ 7 & 4 & 10 & 5\\ 1 & 6 & 4 & 10 \end{bmatrix}\]

[Show Solution]

A = np.array([[4.0, 6, 6, 9],
             [7, 4, 10, 5],
             [1, 6, 4, 10]])

4) find the dimensions of the above matrix and store the number of rows and columns

[Show Solution]

nrows, ncols = A.size

5) print the element in the second row, third column

[Show Solution]

print(A[1, 2])  # remember that python is 0 based indexing, so the 1 corresponds to second row, and 2 to third column

6) store the third column of the above matrix to a new variable

[Show Solution]

y = A[:, 2]  # the colon means all the rows, instead of a single entry

7) print the last row

[Show Solution]

print(A[-1, :])  # recall that -1 means last entry (and -2 is second to last and so on)

8) multiply the matrix by 2

[Show Solution]

B = 2 * A
print(B)

9) extract all entries from A that are greater than 5 into a vector

[Show Solution]

x = A[A > 5]

10) define two arrays: a = [1, 2, 3] and b = [2, 2, 2]. See what happens when you multiply them together.

[Show Solution]

a = np.array([1, 2, 3])
b = np.array([2, 2, 2])
print(a * b)   # this behavior is called broadcasting.  same thing will happen with a matrix.  it will do element-by-element multiplication/division/addition/subtraction.

11) print the maximum entry in x

[Show Solution]

print(a.max())

12) stack the two vectors on top of eachother to create a matrix of size 2x3 (try vstack or concatenate)

[Show Solution]

A = np.vstack([a, b])

13) transpose the resulting matrix

[Show Solution]

B = A.T

14) reverse the order of a

[Show Solution]

print(a[::-1])  # a stride of -1 means reverse, same as in lists.
print(np.flip(a))  # or use a built-in method

15) (challenge): calculate the mean squared error between a and b (subtract them, square result, then compute average of result)

[Show Solution]

np.sum((a - b)**2) / 3
np.mean((a - b)**2)  # or use built in method