Learn

In addition to having built-in support for many linear algebra-related operations, Let’s see how NumPy can create special matrices, such as the identity matrix.

An identity matrix can be constructed using the np.eye() functions, which takes an integer argument that determines the n x n size of the square identity matrix.

# 4x4 identity matrix identity = np.eye(4)

In the output terminal, identity renders as:

[[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]]

A matrix or vector of all zeros can be constructed using the np.zeros() function, which takes in a tuple argument for the shape of the NumPy array filled with zeros.

# 5-element vector of zeros zero_vector = np.zeros((5))

This will output in the terminal as:

[0. 0. 0. 0. 0.]
# 3x2 matrix of zeros zero_matrix = np.zeros((3,2))

This will output in the terminal as:

[[0. 0.] [0. 0.] [0. 0.]]

The transpose of a matrix can be accessed using the .T attribute of a NumPy array as shown below:

A = np.array([[1,2],[3,4]]) A_transpose = A.T

If we print A and A_transpose out in the terminal, A outputs as:

[[1 2] [3 4]]

While A_transpose outputs as:

[[1 3] [2 4]]

Since A_transpose is the transpose of A, the rows and columns are swapped.

Instructions

1.

In script.py, two NumPy arrays are given, A and B, representing two 3x3 matrices. Print out the matrix product of AB and the matrix product of BA.

What does this say about the relationship between matrix A and matrix B?

2.

Print out the transpose of both matrix A and matrix B. What is the first row of each transposed matrix?

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?