Learn

The core of using NumPy effectively for linear algebra is using NumPy arrays. NumPy arrays are n-dimensional array data structures that can be used to represent both vectors (1-dimensional array) and matrices (2-dimensional arrays).

A NumPy array is initialized using the np.array() function, and including a Python list argument or Python nested list argument for arrays with more than one dimension.

For example, the following creates a NumPy array representation of a vector:

v = np.array([1, 2, 3, 4, 5, 6])

We can also create a matrix, which is the equivalent of a two-dimensional NumPy array, using a nested Python list:

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

If we print this NumPy array, it will look like the following:

[[1 2] [3 4]]

Matrices can also be created by combining existing vectors using the np.column_stack() function:

v = np.array([-2,-2,-2,-2]) u = np.array([0,0,0,0]) w = np.array([3,3,3,3]) A = np.column_stack((v, u, w)) print(A)

Output:

[[-2 0 3] [-2 0 3] [-2 0 3] [-2 0 3]]

To access the shape of a matrix or vector once it’s been created as a NumPy array, we call the .shape attribute of the array variable:

A = np.array([[1,2],[3,4]]) print(A.shape)

Here, the output will be:

(2, 2)

since there are two rows and two columns.

To access individual elements in a NumPy array, we can index the array using square brackets. Unlike regular Python lists, we can index into all dimensions in a single square bracket, separating the dimension indices with commas.

Thus in order to index the element equal to 2 in matrix A, we can do the following:

A = np.array([[1,2],[3,4]]) print(A[0,1])

The first index accesses the specific row, while the second index accesses the specific column. Note that rows and columns are zero-indexed. In this example, the output will be the following:

2

We can also select a subset or entire dimension of a NumPy array using a colon. For example, if we want the entire second column of a matrix, we can index the second column and use an empty colon to select every row as such:

A = np.array([[1,2],[3,4]]) print(A[:,1])

Output:

[2 4]

Note: [2 4] is a column vector, but it outputs in the terminal horizontally.

Instructions

1.

In script.py, three NumPy arrays are preloaded in for you: vector_1, vector_1, and vector_3. Use .column_stack() to combine these three arrays into a 4x3 matrix. Save this value to a variable called matrix.

In your matrix:

  • vector_1 should be the first column.
  • vector_2 should be the second column.
  • vector_3 should be the third column.

Print out matrix as well so you see its output in the terminal.

2.

Print out the shape of matrix into the output terminal.

3.

Use array indexing to print out the third column of matrix in the output terminal.

Take this course for free

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