0% found this document useful (0 votes)
5 views16 pages

Vector Operations in Python

The document contains various Python code snippets demonstrating vector and matrix operations using NumPy, including vector addition, dot products, properties of vectors, cosine similarity, distances, and matrix manipulations. It also covers concepts such as Euclidean and Manhattan norms, linear combinations, mean square and absolute errors, and different types of matrices like diagonal and identity matrices. Each section includes code examples and outputs to illustrate the mathematical concepts.

Uploaded by

2504413
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Vector Operations in Python

The document contains various Python code snippets demonstrating vector and matrix operations using NumPy, including vector addition, dot products, properties of vectors, cosine similarity, distances, and matrix manipulations. It also covers concepts such as Euclidean and Manhattan norms, linear combinations, mean square and absolute errors, and different types of matrices like diagonal and identity matrices. Each section includes code examples and outputs to illustrate the mathematical concepts.

Uploaded by

2504413
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Assignment 01

Name Muhammad Osama


Roll No 2504413
Subject Mathematics
Addition of Vector with Scalar

import numpy as np

vector1 = [Link]([2, 4, 6])


vector2 = [Link]([1, 3, 5])
dot1 = [Link](vector1, vector2)
dot2 = vector1 @ vector2
dot3 = [Link](vector1 * vector2)

print("Vector 1:", vector1)


print("Vector 2:", vector2)
print("Dot Product ([Link]):", dot1)
print("Dot Product (@ operator):", dot2)
print("Dot Product (sum):", dot3)

Addition of Vector with Vector

import numpy as np

def add_vectors(v1, v2):


if len(v1) != len(v2):
raise ValueError("Vectors must have the
same length")
return [Link](v1, v2)

# Define vectors
vector1 = [Link]([5, 10, 15, 20, 25])
vector2 = [Link]([2, 4, 6, 8, 10])

try:
result = add_vectors(vector1, vector2)
print("Vector 1:", vector1)
print("Vector 2:", vector2)
print("Resultant Vector:", result)
except ValueError as e:
print("Error:", e)
Dot Product of Two vectors
import numpy as np

# Define two vectors


vector1 = [Link]([2, 4, 6])
vector2 = [Link]([1, 3, 5])

# Compute the dot product


dot_product = [Link](vector1, vector2)

# Display the results


print("Vector 1:", vector1)
print("Vector 2:", vector2)
print("Dot Product:", dot_product)

Commutative property of vector


import numpy as np

# Create two vectors


v1 = [Link]([3, 5, 7])
v2 = [Link]([2, 4, 6])

# Add vectors in both orders


sum1 = v1 + v2
sum2 = v2 + v1

# Display results
print("Vector 1:", v1)
print("Vector 2:", v2)
print("v1 + v2:", sum1)
print("v2 + v1:", sum2)

# Verify commutative property


print("Commutative property holds:",
np.array_equal(sum1, sum2))

Distributive property of Vector

import numpy as np

# Create two vectors


v1 = [Link]([2, 4, 6])
v2 = [Link]([1, 3, 5])
# Define a scalar
s=3

# Apply distributive property


left_result = s * (v1 + v2)
right_result = s * v1 + s * v2

# Show results
print("Vector 1:", v1)
print("Vector 2:", v2)
print("Scalar:", s)
print("s × (v1 + v2):", left_result)
print("s × v1 + s × v2:", right_result)

# Verify distributive property


print("Distributive property holds:",
np.array_equal(left_result, right_result))

Cosine Similarity

import numpy as np

v1 = [Link]([2, 3, 4])
v2 = [Link]([1, 0, 5])

dot_result = [Link](v1, v2)

length_v1 = [Link](v1)
length_v2 = [Link](v2)

cos_sim = dot_result / (length_v1 * length_v2)

print("Vector 1:", v1)


print("Vector 2:", v2)
print("Dot product:", dot_result)
print("Length of v1:", round(length_v1, 3))
print("Length of v2:", round(length_v2, 3))
print("Cosine similarity:", round(cos_sim, 3))
Cosine Distance
import numpy as np

# Create two vectors


v1 = [Link]([2, 3, 4])
v2 = [Link]([1, 0, 5])

# Calculate dot product


dot_result = [Link](v1, v2)

# Compute vector lengths


len_v1 = [Link](v1)
len_v2 = [Link](v2)

# Calculate cosine similarity and distance


cos_sim = dot_result / (len_v1 * len_v2)
cos_dist = 1 - cos_sim

# Display results
print("Vector 1:", v1)
print("Vector 2:", v2)
print("Cosine similarity:", round(cos_sim, 3))
print("Cosine distance:", round(cos_dist, 3))

Inverse of a Vector

import numpy as np

v = [Link]([4, -3, 7])

neg_v = -v

print("Original vector:", v)
print("Negative vector:", neg_v)

print("v + (-v):", v + neg_v)


Scaling of vectors

import numpy as np

# Create a vector
v = [Link]([2, 4, 6])

# Define a scalar
s=3

# Scale the vector


scaled_v = s * v

# Display results
print("Original vector:", v)
print("Scalar:", s)
print("Scaled vector:", scaled_v)

# Compare lengths
len_original = [Link](v)
len_scaled = [Link](scaled_v)

print("\nLength of original:", round(len_original,


3))
print("Length of scaled:", round(len_scaled, 3))

Triangluar Inequality

import numpy as np

# Create two vectors


v1 = [Link]([3, 4])
v2 = [Link]([1, 2])

# Calculate vector lengths


len_v1 = [Link](v1)
len_v2 = [Link](v2)
len_sum = [Link](v1 + v2)

# Display results
print("Vector 1:", v1)
print("Vector 2:", v2)
print("|v1| =", round(len_v1, 3))
print("|v2| =", round(len_v2, 3))
print("|v1 + v2| =", round(len_sum, 3))

# Verify triangle inequality


print("\nTriangle inequality holds:", len_sum <=
(len_v1 + len_v2))

Euclidean Norm

import numpy as np

# Create a vector
v = [Link]([3, 4, 12])

# Calculate its length


length = [Link](v)

# Display results
print("Vector:", v)
print("Length:", round(length, 3))

Manhattan Norm

import numpy as np

# Create a vector
v = [Link]([3, -4, 12])

# Calculate Manhattan length


manhattan_length = [Link](v, ord=1)

# Display results
print("Vector:", v)
print("Manhattan length:", manhattan_length)
Euclidean Distance

import numpy as np

# Create two vectors


v1 = [Link]([2, 3, 5])
v2 = [Link]([6, 7, 9])

# Calculate distance between them


distance = [Link](v1 - v2)

# Display results
print("Vector 1:", v1)
print("Vector 2:", v2)
print("Distance:", round(distance, 3))

Manhattan Distance

import numpy as np
# Define two vectors (points)
A = [Link]([2, 3, 5])
B = [Link]([6, 7, 9])
# Calculate Manhattan distance
manhattan_distance = [Link]([Link](A -
B))
# Display the results
print("Vector A:", A)
print("Vector B:", B)
print("Manhattan Distance between A and
B:", manhattan_distance)

Minkowski Distance

import numpy as np

# Create two vectors


v1 = [Link]([2, 3, 5])
v2 = [Link]([6, 7, 9])

# Calculate Manhattan distance


manhattan_dist = [Link]([Link](v1 - v2))
# Display results
print("Vector 1:", v1)
print("Vector 2:", v2)
print("Manhattan distance:",
manhattan_dist)

Normalization Of a Vector

import numpy as np

# Create two vectors


v1 = [Link]([2, 3, 5])
v2 = [Link]([6, 7, 9])

# Define the order parameter


p=3

# Calculate Minkowski distance


minkowski_dist = [Link]([Link]([Link](v1 -
v2) ** p), 1/p)

# Display results
print("Vector 1:", v1)
print("Vector 2:", v2)
print("Order p:", p)
print("Minkowski distance:",
round(minkowski_dist, 3))

Cauchy Shwarz Inequality

import numpy as np

# Create a vector
v = [Link]([3, 4, 12])

# Calculate its length


length = [Link](v)

# Convert to unit vector


unit_v = v / length

# Display results
print("Original vector:", v)
print("Length:", round(length, 3))
print("Unit vector:", [Link](unit_v, 3))

# Verify unit length


print("Unit vector length:",
round([Link](unit_v), 3))

Linear Combination of Vector

# Import numpy for vector operations


import numpy as np
# Define two vectors
A = [Link]([2, 3, 4])
B = [Link]([1, 5, 2])
# Compute dot product
dot_product = [Link](A, B)
# Compute magnitudes (Euclidean norms)
magnitude_A = [Link](A)
magnitude_B = [Link](B)
# Left-hand side (absolute value of dot product)
lhs = abs(dot_product)
# Right-hand side (product of magnitudes)
rhs = magnitude_A * magnitude_B
# Display results
print("Vector A:", A)
print("Vector B:", B)
print("|A · B| =", round(lhs, 3))
print("||A|| × ||B|| =", round(rhs, 3))
# Verify inequality
print("\nCauchy–Schwarz Inequality holds? ->",
lhs <= rhs)

Mean Square Error

import numpy as np

# Define two vectors


A = [Link]([1, 2])
B = [Link]([3, 1])

# Define scalar coefficients


c1 = 2
c2 = -1
# Compute linear combination
V = c1 * A + c2 * B

# Display results
print("Vector A:", A)
print("Vector B:", B)
print(f"Linear combination (V = {c1}A + {c2}B) =",
V)

Mean Absolute Error

import numpy as np

# Define two vectors


A = [Link]([1, 2])
B = [Link]([3, 1])

# Define scalar coefficients


c1 = 2
c2 = -1

# Compute linear combination


V = c1 * A + c2 * B

# Display results
print("Vector A:", A)
print("Vector B:", B)
print(f"Linear combination (V = {c1}A + {c2}B)
=", V)

Matrix

import numpy as np

# Actual values
actual = [Link]([3, -0.5, 2, 7])

# Predicted values
predicted = [Link]([2.5, 0.0, 2, 8])

# Calculate Mean Square Error


mse = [Link]((actual - predicted) ** 2)
# Display results
print("Actual values: ", actual)
print("Predicted values:", predicted)
print("Mean Square Error (MSE):", mse)

Square matrix

import numpy as np

# Actual values
actual = [Link]([3, -0.5, 2, 7])

# Predicted values
predicted = [Link]([2.5, 0.0, 2, 8])

# Calculate Mean Absolute Error


mae = [Link]([Link](actual - predicted))

# Display results
print("Actual values: ", actual)
print("Predicted values:", predicted)
print("Mean Absolute Error (MAE):", mae)

Null or zero matrix

import numpy as np

# Define a matrix (2 rows, 3 columns)


A = [Link]([[1, 2, 3],
[4, 5, 6]])

# Display the matrix and its properties


print("Matrix A:\n", A)
print("Shape of A (rows, columns):",
[Link])
print("Number of elements in A:", [Link])
print("Transpose of A:\n", A.T)
import numpy as np

# Create a 3x3 zero (null) matrix


A = [Link]((3, 3))

# Display the matrix and its properties


print("Null (Zero) Matrix A:\n", A)
print("Shape of A (rows, columns):",
[Link])
print("Sum of all elements:", [Link](A))

Diagnol matrix

import numpy as np

# Define diagonal elements


diag_elements = [5, 3, 7]

# Create a diagonal matrix


D = [Link](diag_elements)

# Display the matrix and properties


print("Diagonal Matrix D:\n", D)
print("Shape of D:", [Link])
print("Diagonal Elements:", [Link](D))

Scalar Matrix

import numpy as np

# Define scalar value


scalar_value = 4

# Create a 3x3 scalar matrix


S = scalar_value * [Link](3)

# Display the matrix and properties


print("Scalar Matrix S:\n", S)
print("Shape of S:", [Link])
print("Diagonal Elements:", [Link](S))
Identity Matrix
import numpy as np

# Create a 3x3 Identity Matrix


I = [Link](3)

# Display the matrix and properties


print("Identity Matrix I:\n", I)
print("Shape of I:", [Link])

# Verify the property: A * I = A


A = [Link]([[2, 3, 1],
[4, 5, 6],
[7, 8, 9]])

result = [Link](A, I)
print("\nMatrix A:\n", A)
print("\nA * I =\n", result)

Addition and Subtraction of matrix

import numpy as np

# Define two matrices of the same size


A = [Link]([[1, 2],
[3, 4]])

B = [Link]([[5, 6],
[7, 8]])

# Matrix Addition
add_result = A + B

# Matrix Subtraction
sub_result = A - B

# Display results
print("Matrix A:\n", A)
print("\nMatrix B:\n", B)
print("\nA + B =\n", add_result)
print("\nA - B =\n", sub_result)
Product of matrix

import numpy as np

# Define two matrices


A = [Link]([[1, 2],
[3, 4]])

B = [Link]([[5, 6],
[7, 8]])

# Matrix Multiplication (dot product)


product = [Link](A, B)

# Display results
print("Matrix A:\n", A)
print("\nMatrix B:\n", B)
print("\nProduct of A and B (A × B):\n", product)

Inverse of matrix

import numpy as np

# Define a square, non-singular matrix


A = [Link]([[4, 7],
[2, 6]])

# Calculate inverse using numpy


A_inv = [Link](A)

# Verify A * A_inv = Identity Matrix


I = [Link](A, A_inv)

# Display results
print("Matrix A:\n", A)
print("\nInverse of A (A⁻¹):\n", A_inv)
print("\nVerification (A × A⁻¹):\n", I)
Augmented Matrix Form

import numpy as np

# Coefficient matrix A
A = [Link]([[2, 3],
[4, -1]])

# Constant matrix B
B = [Link]([[8],
[2]])

# Create augmented matrix [A|B]


augmented_matrix = [Link]((A, B))

# Display result
print("Augmented Matrix [A|B]:\n",
augmented_matrix)

You might also like