1

I'm having problems making a matrix multiplication algorithm in python3.

This is the code:

def matrixMult(m1, m2):
    result = [[0 for x in range(len(m1))] for x in range(len(m2[0]))]
    # Iterate through rows of m1.
    for i in range(len(m1)):
        # Iterate through columns of m2.
        for j in range(len(m2[0])):
            # Iterate through rows of m2.
            for k in range(len(m2)):
                result[i][j] += m1[i][k] * m2[k][j]   # error occurs here.

    return result

Trying to call it on two random matrices like so:

m = [3, 4, 2]
n = [[13, 9, 7, 15], [8, 7, 4, 6], [6, 4, 0, 3]]
r = matrixMult(m, n)

This results in the TypeError: 'int' object is not subscriptable message.

I added a print(type()) for both the matrices declared above and they are of class 'list'. Did the same for the classes used in the function prototype, class 'list'. Hell, everything is of type 'list'. I don't know what the int object is.

2 Answers 2

3

You are treating m1 as a nested list of integers:

result[i][j] += m1[i][k] * m2[k][j]
#               ^^^^^^^^

It is not; it is merely a simple list of integers. m1[i] then is an integer object and you cannot index integers:

>>> [3, 4, 2][0]
3
>>> [3, 4, 2][0][0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

You probably want to use just i as the index:

result[i][j] += m1[i] * m2[k][j]

or pass in two-dimensional arrays only (so pass in [[3], [4], [2]] rather than [3, 4, 2]).

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

2 Comments

Alright, thank you for the help. How would you suggest I deal with one dimensional matrices?
@tudorv: well, how do you multiply a one-dimensional array with a 2-dimensional array normally? You could pass in a two-dimensional array with just one column each, or you need to adjust your multiplication code to work with one-dimensional arrays.
1

You have the following index operation

m1[i][k]

But m1 was passed in as

m = [3, 4, 2]

It only has 1 dimension to index from, not 2.

1 Comment

Alright, thank you for the help. How would you suggest I deal with one dimensional matrices?

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.