user2863620
user2863620

Reputation: 643

Class python in loop

I created a class of matrix with python:

class MatrixOperation:

    ...

    def create_matrix(self):
        some function for creation of matrix.
        return matrix

    def matrix_vector_multiplication(self, x):
        mat = self.create_matrix()
        return numpy.dot(mat, x)

And:

M = MatrixOperation(...)
x = some set of vector

for i in range(n):
   M.matrix_vector_multiplication(x[i])

The problem is, for each iteration, M.matrix_vector_multiplication(x[i]) will recompute mat = self.create_matrix() before calculating numpy.dot(mat, x), that is unnecessary (since it could be computed once at the beginning). How can I avoid this?

Thanks,

Upvotes: 1

Views: 130

Answers (2)

wwii
wwii

Reputation: 23783

To avoid recreating the matrix each time, create an instance attribute in the class's __init__ method - similar to this.

class Matrix(object):
    def __init__(self, data):
        self.matrix = self.create_matrix(data)
        # or simply
        # self.matrix = np.matrix(data)
    def create_matrix(data):
        # create the_matrix
        return the_matrix
    def do_something(self, x):
        z = some_function(self.matrix, x)
        return z

my_matrix = matrix([[1,2,3,4],[4,3,2,1]])

Upvotes: 3

stoer
stoer

Reputation: 38

just making a copy of the matrix should fix your problem.

import copy


class MatrixOperation:
matrix = None
...

def create_matrix(self):
    if self.matrix is not None:
        return copy.copy(self.matrix)
    some function for creation of matrix.
    self.matrix = matrix
    return matrix

def matrix_vector_multiplication(self, x):
    mat = self.create_matrix()
    return numpy.dot(mat, x)

Upvotes: 1

Related Questions