Basic Matrix Operations

Lesson Introduction

In this lesson, we're diving into basic matrix operations used in machine learning. Understanding matrix operations is crucial because they underpin many algorithms in this field.

Today's goal is to learn matrix addition and scalar multiplication. By the end, you'll be able to add two matrices and multiply a matrix by a scalar using Python and NumPy.

Matrix Addition: Definition and Real-Life Analogy

Matrix addition involves adding corresponding elements from two matrices. Imagine you have two grids of numbers and you want to create a new grid where each number is the sum of the corresponding numbers from the original grids.

Think of each matrix as a seating chart for two classrooms. Adding the matrices is like finding the total number of students in the same seats in both charts.

Matrix Addition: Code Explanation

To add two matrices, they must have the same dimensions. Here's how you can do it in Python with NumPy:

import numpy as np

# Example matrices
m1 = np.array([[1, 2, 3], [4, 5, 6]])
m2 = np.array([[7, 8, 9], [10, 11, 12]])

# Adding matrices
result = m1 + m2
print("Matrix Addition:\n", result)
# Output:
# Matrix Addition:
# [[ 8 10 12]
#  [14 16 18]]
  1. np.array() creates NumPy arrays from the provided lists.
  2. m1 + m2 adds the corresponding elements of m1 and m2.

This sums elements at the same positions in both matrices to form a new matrix. Notice the \n at the end of the string in the print statement. As a reminder, it is a special symbol for a new line.

Practical Example

Suppose you manage inventory for two warehouses. Each warehouse has a matrix representing the quantity of different products in different sections. By adding the two matrices, you can find the total quantity of each product across both warehouses.

import numpy as np

# Warehouse 1 inventory
warehouse1 = np.array([[10, 20, 30], [40, 50, 60]])

# Warehouse 2 inventory
warehouse2 = np.array([[5, 15, 25], [35, 45, 55]])

# Total inventory
total_inventory = warehouse1 + warehouse2
print("Total Inventory:\n", total_inventory)
# Output:
# Total Inventory:
# [[ 15  35  55]
#  [ 75  95 115]]

Scalar Multiplication: Definition and Real-Life Analogy

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal