user2059300
user2059300

Reputation: 361

Python - Multiply matrices with different numbers of columns

I'm trying to multiple two matrices, A and B, where B has more columns than A using python and numpy preferably.

Example:

A = numpy.matrix([[2,3,15],[5,8,12],[1,13,4]], dtype=numpy.object)
B = numpy.matrix([[2,15,6,15,8,14],[17,19,17,7,18,14],[24,14,0,24,2,11]], dtype=numpy.object)

( A*B ) = [[415,297,63,411,100,235],[434,395,166,419,208,314], [319,318,227,202,250,240]]

I've found some examples if they are arrays but none if they are matrices. Can someone help me out?

Upvotes: 1

Views: 180

Answers (2)

Wei-Chih Wang
Wei-Chih Wang

Reputation: 21

You could also use the dot product.

numpy.dot(A,B)

It outputs the same answer that you want.

Upvotes: 2

jcoppens
jcoppens

Reputation: 5440

Did you actually try this? It works fine here:

import numpy as np

def main():
    A = np.matrix([[2,3,15],[5,8,12],[1,13,4]], dtype=np.object)
    B = np.matrix([[2,15,6,15,8,14],[17,19,17,7,18,14],[24,14,0,24,2,11]], dtype=np.object)

    C = ( A*B ) % 26 #  = [[25,11,11,21,22,1],[18,5,10,3,0,2], [7,6,19,20,16,6]]
    print(C)
    return 0

if __name__ == '__main__':
    main()

Prints:

[[25 11 11 21 22 1]
 [18 5 10 3 0 2]
 [7 6 19 20 16 6]]

Upvotes: 3

Related Questions