0

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
6
  • I don't see anything obviously wrong here. Do you have an example input where it gets the wrong answer? Commented Apr 1, 2013 at 2:18
  • no actually, but when I run it I get no output! Commented Apr 1, 2013 at 2:22
  • When you say you get no output, do you mean it doesn't print anything, that the return value is None, or something else? Oh, and in the code you posted, return C should be on column 4 instead of 3. Typo in your post? Commented Apr 1, 2013 at 2:28
  • it returns value none Commented Apr 1, 2013 at 2:49
  • If cols_A != rows_B it will return None Commented Apr 1, 2013 at 3:10

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yeah that was my issue, you're really explained it well Thanks!
0

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

2 Comments

While numpy is definitely the way to go in production code, I'm pretty sure this is an exercise, so going right to a library might defeat the purpose. Moreover, the OP is doing matrix multiplication, not elementwise multiplication, so x*y on two ndarrays wouldn't work. You'd need to use dot or the matrix class.
Mido you need to go to numpy website and download the numpy library. Afther you need install and now you can go to your project and do the import.
0

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]]

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.