Matrix Addition, Subtraction, and Scalar Multiplication with NumPy
Introduction to Matrix Operations with NumPy
Welcome to the lesson on matrix operations! So far, you've explored vector operations with NumPy, gaining skills in manipulating vectors efficiently. In this lesson, you'll expand on that foundation and focus on matrices, which are collections of numbers arranged in rows and columns.
Matrix operations — specifically addition, subtraction, and scalar multiplication — are central in various fields such as computer graphics and machine learning. These operations allow you to perform transformations, encode data, and conduct computations efficiently.
Performing Matrix Addition and Subtraction
Let's begin with matrix addition and subtraction, which involve element-wise arithmetic operations between matrices of the same dimensions. In simpler terms, to add or subtract two matrices, you perform the operations on corresponding elements.
To demonstrate these operations in NumPy, consider the following code example:
Let's break it down:
-
Defining Matrices: Two 2x2 matrices,
matrix_aandmatrix_b, are defined usingNumPy'sarrayfunction. -
Matrix Addition: The
np.addfunction performs element-wise addition, resulting in a new matrix where each element is the sum of the corresponding elements frommatrix_aandmatrix_b. -
Matrix Subtraction: Similarly,
np.subtractperforms element-wise subtraction, resulting in a matrix where each element is the difference of corresponding elements frommatrix_aandmatrix_b.
Note: You can also use the + and - operators for matrix addition and subtraction respectively, which can make the code more concise.
As you can see from the output, the result matrices reflect the sum and difference of the corresponding elements in matrix_a and matrix_b.
Conducting Scalar Multiplication
Scalar multiplication involves multiplying each element of a matrix by a scalar value. This operation can be achieved using straightforward arithmetic in NumPy. Here's how:
Each element of matrix_a is multiplied by the scalar value 3. NumPy automatically applies this operation to each element due to its broadcasting capabilities.
The output shows that every element in matrix_a has been scaled by 3.
