Profile picture

1.3 Vectorized Operations

Last updated: February 20th, 20192019-02-20Project preview

rmotr


Vectorized Operations with NumPy arrays - Exercises

In [ ]:
import numpy as np

green-divider

Exercise 1

Using NumPy, create the following matrices:

  • $ A = \begin{bmatrix} 4 & 4 & 4 \\ 3 & 3 & 3 \\ 2 & 2 & 2 \\ 1 & 1 & 1 \\ \end{bmatrix} $

  • $ b = \begin{bmatrix} 5 & 5 & 5 \end{bmatrix} $

In [ ]:
# your code goes here
In [ ]:
A = np.array([[4, 4, 4],
              [3, 3, 3],
              [2, 2, 2],
              [1, 1, 1]])

b = np.full(3, 5)

green-divider

Exercise 2

Get a new C matrix by adding the b vector over the A matrix.

  • $ C = \begin{bmatrix} 9 & 9 & 9 \\ 8 & 8 & 8 \\ 7 & 7 & 7 \\ 6 & 6 & 6 \\ \end{bmatrix} $
In [ ]:
# your code goes here
In [ ]:
C = A + b

C

green-divider

Exercise 3

Create a new AA matrix with the standardization of the A matrix, to make the data have mean 0, and standard deviation 1.

In [ ]:
# your code goes here

Remember the standardization formula:

$$ \large x'={\frac {x-{\bar {x}}}{\sigma }} $$
In [ ]:
AA = (A - A.mean()) / A.std()

AA

Once you're done with AA, you can check the results with:

In [ ]:
np.round(AA.mean())
In [ ]:
AA.std()

green-divider

Exercise 4

Write the expression to find, for the matrix A, how many values are lower than 3:

In [ ]:
# your code goes here

Remember that you can combine a boolean operation with np.sum.

In [ ]:
np.sum(A < 3)

green-divider

Exercise 5

What is the proportion of values greater than 3 within the A matrix?

In [ ]:
# your code goes here

There are multiple ways of computing this. Using np.sum and the total number of elements, or np.mean. Make sure you check the suggested solutions.

In [ ]:
np.mean(A > 3)
In [ ]:
np.sum(A > 3) / A.size

purple-divider

Notebooks AI
Notebooks AI Profile20060