0

So I have these three complete functions that return the desired row of a matrix, column of a matrix, and dot product of the row and column, and I need to somehow mesh them together in a fourth function in order to find the product of two matrices being multiplied together. Any suggestions?

#Test matrices
A = [[2,4], [7,0], [6,3]]
B = [[3,1], [-1,8], [-3, 3]]
C = [[4,1,9], [6,2,8], [7,3,5]]
D = [[2,9], [5,2], [1,0]]

def row(A,i):
    Z = []
    Z.append(A[i])
    return Z[0]


def col(B,j):
    Z=[]
    for i in range(len(B)):
        Z.append(B[i][j])
    return Z

def dotProduct(x,y):
    prod=0
    for i in range(len(x)):
        prod=prod+x[i]*y[i]
    return prod

def matrixMUL(A, B):
    Z = []
    ....
    return Z
  • What do you mean by mesh them together? – Dexters Mar 29 '13 at 04:21
  • Use them all in matrixMUL(A, B) – user2146234 Mar 29 '13 at 04:27
  • Have you looked into using [NumPy](http://www.numpy.org) and [SciPy](http://www.scipy.org)? They have built-in vectorized functions for all sorts of matrix manipulations. – MattDMo Mar 29 '13 at 13:26
  • @user2146234 you seems to have a lot of matrix operations. As MattDMo suggested you can look into numPY and SciPy See my old question here http://stackoverflow.com/questions/10747935/is-python-capable-of-doing-matlab-equivalent-matrix-operations .. These libraries are just so cool.. And I would suggest you to use a good interpreter if you are trying small functionality. you can also try Spyder which is a good if you are beginner and needs a UI based dev environment. – Dexters Mar 30 '13 at 03:34

1 Answers1

0

Solution with 3 more auxiliary functions:

from functools import partial


#Test matrices

A = [[2,4], [7,0], [6,3]]
B = [[3,1], [-1,8], [-3, 3]]
C = [[4,1,9], [6,2,8], [7,3,5]]
D = [[2,9], [5,2], [1,0]]

def row(A,i):
    Z = []
    Z.append(A[i])
    return Z[0]

def col(B,j):
    Z=[]
    for i in range(len(B)):
        Z.append(B[i][j])
    return Z

def dotProduct(x,y):
    prod=0
    for i in range(len(x)):
        prod=prod+x[i]*y[i]
    return prod

def shape(A):
    num_rows = len(A)
    num_cols = len(A[0]) if A else 0
    return num_rows, num_cols

def matrix_product_entry(A, B, i, j):
    return dotProduct(row(A, i), col(B, j))

def matrix_make(rows, cols, entry_fn):
    return [[entry_fn(i, j) for j in range(cols)]
            for i in range(rows)]

def matrixMUL(A, B):
    n1, k1 = shape(A)
    print(n1, k1)
    n2, k2 = shape(B)
    if k1 != n2:
        raise ArithmeticError("matrices shapes are not compatible!")
    return matrix_make(n1, k2, partial(matrix_product_entry, A, B))

print (matrixMUL(C, D))
# returns [[22, 38], [30, 58], [34, 69]]
Dounchan
  • 319
  • 3
  • 10