2 × 2 matrix
Write a NumPy program to create a 2 × 2 matrix.
[[1 2] [3 4]]
Approach
- From a nested list.
Solution
import numpy as npprint(np.array([[1, 2], [3, 4]]))[[1 2] [3 4]]
Learn the concept
New to this topic? Read the lesson, then come back.
Online Learning Platform
Write a NumPy program to create a 2 × 2 matrix.
[[1 2] [3 4]]
import numpy as npprint(np.array([[1, 2], [3, 4]]))[[1 2] [3 4]]
New to this topic? Read the lesson, then come back.
Write a NumPy program to create a 2 × 3 matrix.
[[1 2 3] [4 5 6]]
import numpy as npprint(np.arange(1, 7).reshape(2, 3))[[1 2 3] [4 5 6]]
New to this topic? Read the lesson, then come back.
Write a NumPy program to create a 3 × 4 matrix.
[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
import numpy as npprint(np.arange(1, 13).reshape(3, 4))[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
New to this topic? Read the lesson, then come back.
Write a NumPy program to print all values of the vector 1-20 except 1.
[ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
v[1:].import numpy as npv = np.arange(1, 21)print(v[1:])[ 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
New to this topic? Read the lesson, then come back.
Write a NumPy program to print all values of the vector 1-20 except 20.
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
import numpy as npv = np.arange(1, 21)print(v[:-1])print(v[v != 20])[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
New to this topic? Read the lesson, then come back.
Write a NumPy program to create a vector with values 1 to 20.
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20] (20,)
np.arange(1, 21).import numpy as npv = np.arange(1, 21)print(v, v.shape)[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20] (20,)
New to this topic? Read the lesson, then come back.
Write a NumPy program to generate 5 random numbers from a standard normal distribution.
[ 0.001 0.299 -0.274 -0.891 -0.455]
rng.standard_normal(5).import numpy as nprng = np.random.default_rng(7)print(rng.standard_normal(5).round(3))[ 0.001 0.299 -0.274 -0.891 -0.455]
New to this topic? Read the lesson, then come back.
Write a NumPy program to generate random numbers between 1 and 2.
[1.774 1.439 1.859 1.697 1.094]
rng.uniform(1, 2, size) with a seeded generator.import numpy as nprng = np.random.default_rng(42)print(rng.uniform(1, 2, 5).round(3))[1.774 1.439 1.859 1.697 1.094]
The seed makes the numbers repeatable.
New to this topic? Read the lesson, then come back.
Write a NumPy program to create a 3 × 3 identity matrix.
[[1 0 0] [0 1 0] [0 0 1]]
np.eye(3).import numpy as npprint(np.eye(3, dtype=int))[[1 0 0] [0 1 0] [0 0 1]]
New to this topic? Read the lesson, then come back.
Write a NumPy program to create a 3 × 3 matrix.
[[1 2 3] [4 5 6] [7 8 9]]
arange(9).reshape(3, 3).import numpy as npprint(np.arange(1, 10).reshape(3, 3))[[1 2 3] [4 5 6] [7 8 9]]
New to this topic? Read the lesson, then come back.