Projects/matrix_class.py
2025-09-12 20:37:36 -07:00

74 lines
2.2 KiB
Python

import numpy as np
class Matrix:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.data = [[0] * cols for _ in range(rows)]
def set_value(self, row, col, value):
if 0 <= row < self.rows and 0 <= col < self.cols:
self.data[row][col] = value
else:
raise IndexError("Index out of bounds")
def get_value(self, row, col):
if 0 <= row < self.rows and 0 <= col < self.cols:
return self.data[row][col]
else:
raise IndexError("Index out of bounds")
def __str__(self):
return '\n'.join([' '.join(map(str, row)) for row in self.data])
def __mul__(self, other):
if self.cols != other.rows:
raise ValueError("Cannot multiply: incompatible dimensions")
result = Matrix(self.rows, other.cols)
for i in range(self.rows):
for j in range(other.cols):
for k in range(self.cols):
result.data[i][j] += self.data[i][k] * other.data[k][j]
return result
myMatrix = Matrix(3, 4)
myOtherMatrix = Matrix(4, 3)
# This will raise an error since multiplication is not defined
multMatrix = myMatrix * myOtherMatrix
print(multMatrix)
# Output: 1 0 0 0
# 0 2 0 0
# 0 0 3 0
matrix_2d = np.full((3, 3), 5)
print(f'3x3 matrix filled with 5:\n{matrix_2d}')
# Create a 5x5 identity matrix
matrix_identity = np.eye(5)
print(f'5x5 identity matrix:\n{matrix_identity}')
#create a 5x1 column vector
column_vector = np.full((5, 1), 3)
print(f'5x1 column vector:\n{column_vector}')
def __multiply__(matrix1, matrix2):
return matrix1 * matrix2
# Creating a 2D matrix using the Matrix class
myMatrix = Matrix(2, 2)
# Setting values in the matrix
myMatrix.set_value(0, 0, 1)
myMatrix.set_value(0, 1, 4)
myMatrix.set_value(1, 0, -3)
myMatrix.set_value(1, 1, 2)
myOtherMatrix = Matrix(2, 2)
myOtherMatrix.set_value(0, 0, -5)
myOtherMatrix.set_value(0, 1, 6)
myOtherMatrix.set_value(1, 0, 7)
myOtherMatrix.set_value(1, 1, -8)
# Example usage of the Matrix multiply class
result = __multiply__(myMatrix, myOtherMatrix)
print(f'Result of multiplying myMatrix and myOtherMatrix:\n{result}')