Python Encyclopedia for Academics
  • Course Outline
  • Artificial Intelligence
    • Data Science Foundation
      • Python Programming
        • Introduction and Basics
          • Variables
          • Print Function
          • Input From User
          • Data Types
          • Type Conversion
        • Operators
          • Arithmetic Operators
          • Relational Operators
          • Bitwise Operators
          • Logical Operators
          • Assignment Operators
          • Compound Operators
          • Membership Operators
          • Identity Operators
      • Numpy
        • Vectors, Matrix
        • Operations on Matrix
        • Mean, Variance, and Standard Deviation
        • Reshaping Arrays
        • Transpose and Determinant of Matrix
      • Pandas
        • Series and DataFrames
        • Slicing, Rows, and Columns
        • Operations on DataFrames
        • Different wayes to creat DataFrame
        • Read, Write Operations with CSV files
      • Matplotlib
        • Graph Basics
        • Format Strings in Plots
        • Label Parameters, Legend
        • Bar Chart, Pie Chart, Histogram, and Scatter Plot
  • Machine Learning Algorithms
    • Regression Analysis In ML
      • Regression Analysis in Machine Learning
      • Proof of Linear Regression Formulas
      • Simple Linear Regression Implementation
      • Multiple Linear Regression
      • Advertising Dataset Example
      • Bike Sharing Dataset
      • Wine Quality Dataset
      • Auto MPG Dataset
    • Classification Algorithms in ML
      • Proof of Logistic Regression
      • Simplified Mathematical Proof of SVM
      • Iris Dataset
  • Machine Learning Laboratory
    • Lab 1: Titanic Dataset
      • Predicting Survival on the Titanic with Machine Learning
    • Lab 2: Dow Jones Index Dataset
      • Dow Jones Index Predictions Using Machine Learning
    • Lab 3: Diabetes Dataset
      • Numpy
      • Pandas
      • Matplotlib
      • Simple Linear Regression
      • Simple Non-linear Regression
      • Performance Matrix
      • Preprocessing
      • Naive Bayes Classification
      • K-Nearest Neighbors (KNN) Classification
      • Decision Tree & Random Forest
      • SVM Classifier
      • Logistic Regression
      • Artificial Neural Network
      • K means Clustering
    • Lab 4: MAGIC Gamma Telescope Dataset
      • Classification in ML-MAGIC Gamma Telescope Dataset
    • Lab 5: Seoul Bike Sharing Demand Dataset
      • Regression in ML-Seoul Bike Sharing Demand Dataset
    • Lab 6: Medical Cost Personal Datasets
      • Predict Insurance Costs with Linear Regression in Python
    • Lab 6: Predict The S&P 500 Index With Machine Learning And Python
      • Predict The S&P 500 Index With Machine Learning And Python
  • Artificial Neural Networks
    • Biological Inspiration vs. Artificial Neurons
    • Review linear algebra and calculus essentials for ANNs
    • Activation Function
  • Mathematics
    • Pre-Calculus
      • Factorials
      • Roots of Polynomials
      • Complex Numbers
      • Polar Coordinates
      • Graph of a Function
    • Calculus 1
      • Limit of a Function
      • Derivative of Function
      • Critical Points
      • Indefinite Integrals
  • Calculus 2
    • 3D Coordinates and Vectors
    • Vectors and Vector Operations
    • Lines and Planes in Space (3D)
    • Partial Derivatives
    • Optimization Problems (Maxima/Minima) in Multivariable Functions
    • Gradient Vectors
  • Engineering Mathematics
    • Laplace Transform
  • Electrical & electronics Eng
    • Resistor
      • Series Resistors
      • Parallel Resistors
    • Nodal Analysis
      • Example 1
      • Example 2
    • Transient State
      • RC Circuit Equations in the s-Domain
      • RL Circuit Equations in the s-Domain
      • LC Circuit Equations in the s-Domain
      • Series RLC Circuit with DC Source
  • Computer Networking
    • Fundamental
      • IPv4 Addressing
      • Network Diagnostics
  • Cybersecurity
    • Classical Ciphers
      • Caesar Cipher
      • Affine Cipher
      • Atbash Cipher
      • Vigenère Cipher
      • Gronsfeld Cipher
      • Alberti Cipher
      • Hill Cipher
Powered by GitBook
On this page
  • 1. What Is a Vector?
  • 2. Vector Representation
  • 3. Types of Vectors
  • 4. Vector Operations
  • 5. Vector Visualization in 2D & 3D
  • 6. Plot Vector Addition Graphically
  1. Calculus 2

Vectors and Vector Operations

Nerd Cafe

1. What Is a Vector?

A vector is a mathematical quantity that has:

  • Magnitude (length)

  • Direction

Example:

Displacement of 5 km North is a vector, but just 5 km is a scalar.

2. Vector Representation

A vector in 2D space is written as:

V1→=[v1v2]\overrightarrow{V_{1}}=\begin{bmatrix} v_{1} \\ v_{2} \end{bmatrix}V1​​=[v1​v2​​]
import numpy as np

v = np.array([3, 4])
print(v)

Output:

[3 4]

3. Types of Vectors

  • Zero vector: [0,0]

  • Unit vector: Magnitude is 1

  • Equal vectors: Same magnitude and direction

  • Opposite vectors: Same magnitude, opposite direction

4. Vector Operations

4.1 Addition & Subtraction

Mathematics:

A→+B→=[a1+b1a2+b2]\overrightarrow{A}+\overrightarrow{B}=\begin{bmatrix} a_{1}+b_{1} \\ a_{2}+b_{2} \end{bmatrix}A+B=[a1​+b1​a2​+b2​​]

Python:

A = np.array([2, 3])
B = np.array([4, 1])

add = A + B
sub = A - B

print("Addition:", add)
print("Subtraction:", sub)

Output:

Addition: [6 4]
Subtraction: [-2  2]

4.2 Scalar Multiplication

Mathematics:

k.A→=[k.a1k.a2]k.\overrightarrow{A}=\begin{bmatrix} k.a_{1} \\ k.a_{2} \end{bmatrix}k.A=[k.a1​k.a2​​]

Python:

v = np.array([2, -1])
k = 3
scaled = k * v

print("Scaled vector:", scaled)

Output:

Scaled vector: [ 6 -3]

4.3 Dot Product

Mathematics:

A→.B→=a1.b1+a2.b2\overrightarrow{A}.\overrightarrow{B}=a_{1}.b_{1}+a_{2}.b_{2}A.B=a1​.b1​+a2​.b2​

Result is a scalar.

Python:

a = np.array([1, 2])
b = np.array([3, 4])

dot = np.dot(a, b)
print("Dot product:", dot)

Output:

Dot product: 11

Use to find angle or test orthogonality.

4.4 Cross Product (Only in 3D)

Mathematics:

A→×B→=[a2b3−a3b2a3b1−a1b3a1b2−a2b1]\overrightarrow{A}\times \overrightarrow{B}=\begin{bmatrix} a_{2}b_{3}-a_{3}b_{2} \\ a_{3}b_{1}-a_{1}b_{3} \\ a_{1}b_{2}-a_{2}b_{1} \end{bmatrix}A×B=​a2​b3​−a3​b2​a3​b1​−a1​b3​a1​b2​−a2​b1​​​

Python:

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

cross = np.cross(a, b)
print("Cross product:", cross)

Output:

Cross product: [-3  6 -3]

4.5 Magnitude or Norm

Mathematics:

∣A→∣=a12+a22\left| \overrightarrow{A} \right|=\sqrt{{a_{1}^{2}}+{a_{2}^{2}}}​A​=a12​+a22​​

Python:

v = np.array([3, 4])
magnitude = np.linalg.norm(v)

print("Magnitude:", magnitude)

Output:

Magnitude: 5.0

4.6 Unit Vector

Mathematics:

A^=A→∣A→∣\hat{A}=\frac{\overrightarrow{A}}{\left| \overrightarrow{A} \right|}A^=​A​A​

Python:

v = np.array([3, 4])
unit_v = v / np.linalg.norm(v)

print("Unit vector:", unit_v)

Output:

Unit vector: [0.6 0.8]

4.7 Angle Between Vectors

Mathematics:

θ=cos−1(A→.B→∣A→∣∣B→∣)\theta=cos^{-1}(\frac{\overrightarrow{A}.\overrightarrow{B}}{|\overrightarrow{A}||\overrightarrow{B}|})θ=cos−1(∣A∣∣B∣A.B​)

Python:

from numpy import dot, arccos
from numpy.linalg import norm
from numpy import rad2deg

a = np.array([1, 2])
b = np.array([2, 3])

cos_theta = dot(a, b) / (norm(a) * norm(b))
angle_rad = arccos(cos_theta)
angle_deg = rad2deg(angle_rad)

print("Angle (degrees):", angle_deg)

Output:

Angle (degrees): 7.125016348901757

5. Vector Visualization in 2D & 3D

5.1 Plotting a Vector in 2D

Let’s plot a vector from the origin to point (x, y).

Python Code:

import numpy as np
import matplotlib.pyplot as plt

# Define vector
v = np.array([4, 3])
origin = np.array([0, 0])  # Starting point (0,0)

# Plot
plt.figure(figsize=(6, 6))
plt.quiver(*origin, v[0], v[1], angles='xy', scale_units='xy', scale=1, color='blue')
plt.xlim(-1, 6)
plt.ylim(-1, 6)
plt.grid()
plt.gca().set_aspect('equal')
plt.title("2D Vector Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

plt.quiver() draws an arrow from the origin.

Output:

5.2 Plotting Multiple Vectors in 2D

# Two vectors
a = np.array([2, 3])
b = np.array([4, 1])

# Plot
plt.figure(figsize=(6, 6))
plt.quiver(0, 0, a[0], a[1], color='r', angles='xy', scale_units='xy', scale=1, label='Vector a')
plt.quiver(0, 0, b[0], b[1], color='g', angles='xy', scale_units='xy', scale=1, label='Vector b')
plt.xlim(-1, 6)
plt.ylim(-1, 6)
plt.grid()
plt.gca().set_aspect('equal')
plt.title("Multiple Vectors in 2D")
plt.legend()
plt.show()

Output:

5.3 Plotting Vectors in 3D

from mpl_toolkits.mplot3d import Axes3D

# 3D Vector
v = np.array([2, 3, 4])

# Plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.quiver(0, 0, 0, v[0], v[1], v[2], color='purple')

# Axes limits
ax.set_xlim([0, 5])
ax.set_ylim([0, 5])
ax.set_zlim([0, 5])
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
ax.set_title("3D Vector Plot")
plt.show()

6. Plot Vector Addition Graphically

a = np.array([2, 1])
b = np.array([1, 3])
c = a + b  # Resultant

plt.figure(figsize=(6, 6))
plt.quiver(0, 0, a[0], a[1], color='r', scale=1, angles='xy', scale_units='xy', label='a')
plt.quiver(a[0], a[1], b[0], b[1], color='g', scale=1, angles='xy', scale_units='xy', label='b')
plt.quiver(0, 0, c[0], c[1], color='b', scale=1, angles='xy', scale_units='xy', label='a + b')

plt.xlim(-1, 5)
plt.ylim(-1, 5)
plt.grid()
plt.gca().set_aspect('equal')
plt.legend()
plt.title("Vector Addition (Head-to-Tail Method)")
plt.show()

Output:

Previous3D Coordinates and VectorsNextLines and Planes in Space (3D)

Last updated 1 month ago