Mido
Mido

Reputation: 39

matrix using python

I'm new to python and I'm writing a program fro matrix but there is a problem I don't know to get the right output and I need help with it. this is the question:Given a nXn matrix A and a kXn matrix B find AB . and here is what I have so far. Thank you in advance

def matrixmult (A, B):
    rows_A = len(A)
    cols_A = len(A[0])
    rows_B = len(B)
    cols_B = len(B[0])

    if cols_A != rows_B:
      print "Cannot multiply the two matrices. Incorrect dimensions."
      return

    # Create the result matrix
    # Dimensions would be rows_A x cols_B
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    print C

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k]*B[k][j]
    return C

Upvotes: 0

Views: 1013

Answers (3)

Vlad Bezden
Vlad Bezden

Reputation: 89499

One liner:

def matrixmult(m1, m2):
    return [
        [sum(x * y for x, y in zip(m1_r, m2_c)) for m2_c in zip(*m2)] for m1_r in m1
    ]

Explanation:

zip(*m2) - gets a column from the second matrix

zip(m1_r, m2_c) - creates tuple from m1 row and m2 column

sum(...) - sums multiplication row * col

Test:

m1 = [[1, 2, 3], [4, 5, 6]]
m2 = [[7, 8], [9, 10], [11, 12]]
result = matrixmult(m1, m2)
assert result == [[58, 64], [139, 154]]

Upvotes: 0

dawg
dawg

Reputation: 103694

Your function:

def matrixmult (A, B):
    rows_A = len(A)
    cols_A = len(A[0])
    rows_B = len(B)
    cols_B = len(B[0])

    if cols_A != rows_B:
      print "Cannot multiply the two matrices. Incorrect dimensions."
      return

    # Create the result matrix
    # Dimensions would be rows_A x cols_B
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    print C

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k]*B[k][j]
    return C

Which appears to be the same as this function.

If I run this:

matrix=[[1,2,3],
    [4,5,6],
    [7,8,9]]

print matrixmult(matrix, matrix)    # that is your function...

It returns:

[[30, 36, 42], [66, 81, 96], [102, 126, 150]]

This is the same as Numpy:

import numpy as np

a=np.array(matrix)
b=np.array(matrix)
print np.dot(a,b)
#  [[ 30  36  42]
    [ 66  81  96]
    [102 126 150]]

And the same as the matrix multiply more tersely stated:

def mult(mtx_a,mtx_b):
    tpos_b = zip( *mtx_b)
    rtn = [[ sum( ea*eb for ea,eb in zip(a,b)) for b in tpos_b] for a in mtx_a]
    return rtn

So -- it is probably your input data that is the issue.

Upvotes: 1

Carlos Neves
Carlos Neves

Reputation: 67

Use numPy library to solve your problem.

import numpy as np

x = np.array( ((2,3), (3, 5)) )

y = np.array( ((1,2), (5, -1)) )

print x * y

array([[ 2, 6], [15, -5]])

More examples: http://www.python-course.eu/matrix_arithmetic.php

Download numPy: http://scipy.org/Download

Upvotes: 0

Related Questions