Basic Vector Operations

Lesson Introduction

Welcome! Today, we're diving into basic vector operations, which are foundational to your journey in machine learning. Understanding these operations will help you grasp more complex concepts later on. Our goals are to learn vector addition and scalar multiplication. We'll see why these operations are essential, learn how to implement them in Python, and understand their real-world applications.

Vector Addition: Introduction and Example

Imagine you have two lists of numbers. You want to combine them by adding corresponding numbers together. That's vector addition. Let's say we have vector v1=[1,2,3]\mathbf{v_1} = [1, 2, 3] and vector v2=[4,5,6]\mathbf{v_2} = [4, 5, 6]. Adding these vectors gives us another vector where each element is the sum of the corresponding elements. Note: The vectors must be of the same length to perform this addition.

So, v1+v2\mathbf{v_1} + \mathbf{v_2} = [1+4, 2+5, 3+6] = [5, 7, 9].

Consider two delivery trucks: Truck A and Truck B. Truck A delivers 1, 2, and 3 packages to three different locations respectively, while Truck B delivers 4, 5, and 6 packages to the same locations. By using vector addition, we can determine the total number of packages delivered to each location as follows: [1+4, 2+5, 3+6] = [5, 7, 9]. This means the total packages delivered to each location are 5, 7, and 9 respectively.

Vector Addition: Python Code

Here's how we can implement the vector addition in python:

Python
import numpy as np

# Vector addition using numpy
v1 = np.array([1, 2, 3])
v2 = np.array([4, 5, 6])

print("Vector Addition:", v1 + v2)  # Vector Addition: [5 7 9]

Let's break down the code:

  • np.array([1, 2, 3]) and np.array([4, 5, 6]) create numpy arrays for v1 and v2.
  • The expression v1 + v2 performs element-wise addition, resulting in [5, 7, 9].

Scalar Multiplication: Introduction and Example

Now let's discuss scalar multiplication. Imagine you have a list of numbers and you want to multiply each number by a constant value (scalar). For example, if v=[2,4,6]\mathbf{v} = [2, 4, 6] and the scalar is 3, then multiplying each element by 3 gives us 3v=[6,12,18] \mathbf{3v} = [6, 12, 18].

Imagine you are running a business and you have a list of product prices that are expected to increase by a fixed percentage (e.g., 20%). If the current prices are [10, 20, 30] dollars and you want to apply a 20% increase, you would multiply each price by 1.2. The new prices would be [10×1.2,20×1.2,30×1.2]=[12,24,36][10 \times 1.2, 20 \times 1.2, 30 \times 1.2] = [12, 24, 36] dollars.

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