How to Create a Matrix Class in Python?

Estimated read time 2 min read

To create a matrix class in Python, you can define a new class that contains the necessary attributes and methods for manipulating matrices. Here’s an example:

class Matrix:
    def __init__(self, rows, cols):
        self.rows = rows
        self.cols = cols
        self.data = [[0 for j in range(cols)] for i in range(rows)]
    
    def __repr__(self):
        return f"Matrix({self.rows}, {self.cols}, {self.data})"
    
    def __getitem__(self, index):
        return self.data[index]
    
    def __setitem__(self, index, value):
        self.data[index] = value
    
    def __add__(self, other):
        result = Matrix(self.rows, self.cols)
        for i in range(self.rows):
            for j in range(self.cols):
                result[i][j] = self.data[i][j] + other[i][j]
        return result
    
    def __sub__(self, other):
        result = Matrix(self.rows, self.cols)
        for i in range(self.rows):
            for j in range(self.cols):
                result[i][j] = self.data[i][j] - other[i][j]
        return result
    
    def __mul__(self, other):
        if isinstance(other, Matrix):
            if self.cols != other.rows:
                raise ValueError("Matrices cannot be multiplied.")
            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[i][j] += self.data[i][k] * other[k][j]
            return result
        else:
            result = Matrix(self.rows, self.cols)
            for i in range(self.rows):
                for j in range(self.cols):
                    result[i][j] = self.data[i][j] * other
            return result

In this example, we define a class Matrix that contains the following methods:

  • __init__(self, rows, cols): Initializes a new matrix with the given number of rows and columns, and sets all elements to 0.
  • __repr__(self): Returns a string representation of the matrix in the format Matrix(rows, cols, data).
  • __getitem__(self, index): Gets the element at the given row and column index.
  • __setitem__(self, index, value): Sets the element at the given row and column index to the given value.
  • __add__(self, other): Adds two matrices element-wise and returns the result.
  • __sub__(self, other): Subtracts two matrices element-wise and returns the result.
  • __mul__(self, other): Multiplies two matrices together or multiplies a matrix by a scalar and returns the result.

Note that this is just a basic implementation of a matrix class and there are many other methods and operations that can be added. You can customize this class to suit your specific needs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply