Solutions to Chapter 7 Exercises
Contents
10.5. Solutions to Chapter 7 Exercises#
import numpy as np
10.5.1. Exercise 1#
Do you think 2**np.array([1,2,3])
will work?
# write your code here
2**np.array([1,2,3])
array([2, 4, 8])
The answer is YES. It will work due to broadcasting. So the scalar 2 will be broadcasted to an array [2,2,2] and then the element-wise rise to power happens to get the result.
10.5.2. Exercise 2#
Using numpy arrays find the cubes of the numbers from 11 to 19.
# write your code here
np.arange(11,20)**3
array([1331, 1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859])
10.5.3. Exercise 3#
Given the 3x3 matrix of numbers from 1 to 9, find the average per row.
matrix = np.arange(1,10).reshape(3,3)
# write your code here
matrix.mean(axis = 1)
array([2., 5., 8.])
10.5.4. Exercise 4#
Given the 3x3 matrix of numbers from 1 to 9, find the average per columns.
matrix = np.arange(1,10).reshape(3,3)
# write your code here
matrix.mean(axis = 0)
array([4., 5., 6.])
10.5.5. Exercise 5#
Given the 3x3 matrix of numbers from 1 to 9, find a way using slicing to select the highlighted elements in the Fig. 10.1.

Fig. 10.1 Special Slicing#
matrix = np.arange(1,10).reshape(3,3)
# write your code here
matrix[[[0,0], [2,2]], [[0,2],[0,2]]]
array([[1, 3],
[7, 9]])
To better understand this, do an element-wise matching of the indices: {[0,0], [0,2], [2,0], [2,2]}. These will be the indices of the elements that will be selected.