1

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,

3
  • Should create_matrix return the matrix, or could it make it an instance attribute? Commented Jul 9, 2014 at 13:46
  • What do you mean once? by instance? by process like static variable in Java? Commented Jul 9, 2014 at 13:57
  • I mean the matrix was created in the first iteration. For the 2, 3... iteration, I just do matrix_vector_multiplication, do not repeat the creation of matrix. Commented Jul 9, 2014 at 14:01

2 Answers 2

3

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.