Matrix multiplication

https://colab.research.google.com/drive/1dQ2l2L_8dFUyjxuEcmPz55jkaE6vfB9T#scrollTo=2WSUTcZjt_Pe&line=5&uniqifier=1

Here is the link of a section of google colab where I have tried a recursive version of the Exercise of list.
Now I am just curious, whether this is an efficient way of doing this or not…
Here I am requesting you to go through the code once.
Thank you.

Could you please post the code here? (instead of a link)

1 Like

Please give grant to access for anyone

1 Like

You can also have a look at this:

def matrix_square(n):

"""

Calculate the nth power of the matrix, A=[[1,1],[1,0]]

"""

A=[[1,1],[1,0]]

B = [item[:] for item in A]

C = [item[:] for item in A]

for count in range(n-1):

    for row in range(2):

        for col in range(2):

            m=0

            for k in range(2):

                n= A[row][k]*B[k][col]

                m=m+n   

            C[row][col] = m

    B=[item[:] for item in C]

return B

THIS IS THE CODE

Dont know how to give access

@Odibumba,
Under the constraint of implementing this exercise using only lists, I think this code is fine from optimization perspective.

However, the improvisation could be:

  1. Not restricting the input matrix A to only one predefined matrix
  2. A generic implementation of matrix multiplier function which can perform multiplication of matrices of (p,q) X (q, r) dimension.
  3. Breaking down each of these utilities into individually testable functions.
  4. Test by providing different input matrices.

Though these are not required from the exercise point of view, it is a good chance to familiarize with python.

If you are interested, I can post code here.

2 Likes

How is this?

def is_matrix_of_size (matrix, rows, cols) :
  """Checks whether `matrix` is a matrix with `rows` rows and `cols` coloumns."""
  i = 0  
  for row in matrix :
    if len(row) != cols :
      return False
    i += 1
  return i == rows

def product(A, B, m, p, n) :
  """Multiplies the matrices `A`: `m` by `n`, `B` : `n` by `p`."""
  if not(is_matrix_of_size(A, m, n)) or not(is_matrix_of_size(B, n, p)) :
    raise ValueError("Matrices not of dimensions " + str(m) + " by " + str(n) + " and " + str(n) + " by " + str(p) + ".")
  return [[sum( (A[i][j] * B[j][k] for j in range(n)) )
               for k in range(p)]
              for i in range(m)]

def id_matrix (dim) :
  """Returns the identity matrix of dimensions `dim`-by-`dim`."""
  return [ [(1 if i==j else 0)
                for j in range(dim)]
              for i in range(dim)]

# Exponentiation by repeated squaring
def power (matrix, exp) :
  """Raises `matrix` to the power `exp`, which must be non-negative.
If `exp == 0`, returns an identity matrix with `len(matrix)` rows.
If `exp == 1`, returns `matrix`.
Else, actually raises `matrix` to the power of `exp`, checking that it is in fact a matrix.""" 
  try:
    if (exp < 0) :
      raise ValueError("Exponent is negative: " + str(exp))
    dim = len(matrix)
    if (exp == 0) :
      return id_matrix(dim)
    exp -= 1
    acc = matrix
    while (exp > 0) :
      if (exp % 2) : acc = product(acc, matrix, dim,dim,dim)
      matrix = product(matrix, matrix, dim,dim,dim)
      exp = exp // 2
    return acc
  except:
    print("Within the function matrix.power(matrix, exp):")
    raise
1 Like

yeah sure.
I would really appreciate that

@Odibumba
Here is my implementation:

def get_number_rows_columns(m):
    '''
    given matrix m, return the number of rows and columns
    '''
    rows = len(m)
    columns_in_each_row = [len(item) for item in m]
    columns = columns_in_each_row[0] if (all(element == columns_in_each_row[0] for element in columns_in_each_row)) else 0
    return rows, columns

def isSquareMatrix(m):
    '''
    This functions checks if givem matrix m is a square matrix or not
    '''
    rows,columns = get_number_rows_columns(m)
    return True if (rows == columns) else False

def get_dot_product(row,column):
    '''
    given 2 lists row and column, performs sum_product of each elements
    '''
    dot_product = 0;
    for i in range(len(row)):
        dot_product += row[i]*column[i]
    return dot_product

def matrix_multiplier(A,B):
    '''
    Multiplies 2 matrices A and B,
    Only if the matrices are of p x q, q x r dimension respectively.
    '''
    rowsA, columnsA = get_number_rows_columns(A)
    rowsB, columnsB = get_number_rows_columns(B)

    product_matrix = []
    
    if (columnsA ==  rowsB ):
        for i in range(rowsA):
            product_row = []
            row = A[i]
            for j in range(columnsB):
                column = [item[j] for item in B]
                product_row.append(get_dot_product(row,column))
            product_matrix.append(product_row)
        return product_matrix

    else:
        print("Given matrix is not square matrix and hence cannot be multiplied onto itself")
        return None

def power_of_matrix(A,n):
    '''
    Finds the n th power of matrix A.
    A must be a square matrix
    n must be >= 1
    '''
    if (isSquareMatrix(A)):
        product = A
        if n > 1:
            for i in range(1,n):
                product = matrix_multiplier(product,A)
        elif n < 1:
            print ("n must be > 0")
            return None
        return product
#===========================================
#Matrices used for testing
x = [[1,1],[1,0]]
y = [[1,2,3],[4,5,6],[7,8,9]]
z = [[1,2,3],[4,5,6]]

"""##Test for List Exercises
### Test get_number_rows_columns()
"""

print(get_number_rows_columns(x))
print(get_number_rows_columns(y))
print(get_number_rows_columns(z))

"""Test isSquareMatrix()"""

print(isSquareMatrix(x))
print(isSquareMatrix(y))
print(isSquareMatrix(z))

"""Test get_dot_product()"""

print(get_dot_product(x[0],x[1]))
print(get_dot_product(y[0],y[1]))

"""Test matrix_multiplier()"""

m = [[1,2,4],[5,6,7]]
n = [[1,2],[3,4],[5,6]]
print(matrix_multiplier(m,n))

"""Test power_of_matrix()"""

print("input matrix is", x)
for n in range(1,11):
    print(power_of_matrix(x,n))
print("=============================")    
print("input matrix is", y)
for n in range(1,11):
    print(power_of_matrix(y,n))
print("=============================")    
print("input matrix is", z)
for n in range(1,11):
    print(power_of_matrix(z,n))
print("=============================")

Quite interesting, thanks for posting :+1: