= [1, 2, 3, 4, 5, 6]
lst
= [[1, 2, 3], [4, 5, 6]]
matrix
print(lst)
print(matrix)
[1, 2, 3, 4, 5, 6]
[[1, 2, 3], [4, 5, 6]]
In Python, vectors are typically represented by lists and matrices by nested lists. For example, the vector
\[ (1, 2, 3, 4, 5, 6) \]
and the matrix
\[ \begin{pmatrix} 1 & 2 & 3\\ 4 & 5 & 6 \end{pmatrix} \]
can be natively created in Python like this:
= [1, 2, 3, 4, 5, 6]
lst
= [[1, 2, 3], [4, 5, 6]]
matrix
print(lst)
print(matrix)
[1, 2, 3, 4, 5, 6]
[[1, 2, 3], [4, 5, 6]]
If you want to use NumPy arrays, you can use the np.array()
command:
= np.array([1, 2, 3, 4, 5, 6])
lst
= np.array([[1, 2, 3], [4, 5, 6]])
matrix
print(lst)
print(matrix)
[1 2 3 4 5 6]
[[1 2 3]
[4 5 6]]
If you look at the output from the print()
commands, two things stand out. First, the commas are gone, and second, the matrix is printed in a clean, readable format.
It is also possible to create higher-dimensional arrays. This requires another level of nesting. In the following example, a three-dimensional matrix is created:
= np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) matrix_3d
It is considered good practice to always initialize arrays. NumPy offers three functions to create pre-initialized arrays. Alternatively, arrays can be initialized with fixed values. You can use np.zeros()
to set all values to 0 or np.ones()
to initialize all values with 1. These functions take the shape in the form [rows, columns]
. If you want to initialize all elements with a specific value, use the np.full()
function.
2,3]) np.zeros([
array([[0., 0., 0.],
[0., 0., 0.]])
2,3]) np.ones([
array([[1., 1., 1.],
[1., 1., 1.]])
2,3],7) np.full([
array([[7, 7, 7],
[7, 7, 7]])
The trick is to initialize an array with np.ones()
and then multiply the array by the number x
. In the following example, x = 5
:
2,3]) * 5 np.ones([
array([[5., 5., 5.],
[5., 5., 5.]])
If you want to create a vector with evenly spaced values, e.g., for an axis in a plot, NumPy offers two options. Use np.linspace(start, stop, #values)
or np.arange(start, stop, step)
to generate such arrays.
0,1,11) np.linspace(
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
0,10,2) np.arange(
array([0, 2, 4, 6, 8])
Create one NumPy array for each of the following tasks: