This tutorial focuses on creating vectors and matrices with the NumPy package.
Import the library:
import numpy as np
Creating a row vector and a column vector:
vector_row = np.array([1, 2, 3, 4, 5])
print("Vector Row:", vector_row)
vector_column = np.array([[1], [2], [3], [4], [5]])
print("Vector Column:\\n", vector_column)
Output:
Vector Row: [1 2 3 4 5]
Vector Column:
[[1]
[2]
[3]
[4]
[5]]
Matrix is a two-dimensional array data structure constructed as a rectangular table-like shape with rows and columns. The elements in the matrix are often called entries.
Various forms of matrix can be created using NumPy.
np.array()
# Create matrix with np.array
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("Matrix:\\n", matrix)
Output:
Matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]
If the 2D array is not at the same size, an ERROR will raise:
matrix = np.array([[1, 2], [4, 5, 6], [7, 8, 9]]) print("Matrix:\\n", matrix)