How do you multiply a 2d matrix in python?

import numpy
a = numpy.arange[9].reshape[3,3]
b = numpy.arange[60].reshape[20,3]
c1 = numpy.dot[b, a.T] # as in the answer of senderle
c2 = numpy.einsum['ji,ki->kj',a,b]

and the resulting c1 and c2 are both the same as what you wish [verified with your c[i] = np.dot[a, b[i]] ]

the advantage of numpy.einsum is that this trick 'ji,ki->kj' telling what has to be done on what dimension also works for larger dimensions.

more explanation on einsum

for example, if you want to do the following operation:

a = numpy.arange[60.].reshape[3,4,5]
b = numpy.arange[24.].reshape[4,3,2]
d1 = numpy.zeros[[5,2]]

for i in range[5]:
    for j in range[2]:
        for k in range[3]:
            for n in range[4]:
                d1[i,j] += a[k,n,i] * b[n,k,j]

you can do the same thing much faster by doing:

d2 = numpy.einsum['kni,nkj->ij', a, b] 
# the 'kni,nkj->ij' is what you otherwise do with the indices as in 
# d1[i,j] += a[k,n,i] * b[n,k,j]

or if you do not like this way of specifying what has to happen, you can also use numpy.tensordot instead of numpy.einsum, and specify the axes as follows:

d3 = numpy.tensordot[a,b, axes=[[1,0],[0,1]]] 

so this einsum method is very general and can be used to shortcut for-loops [that are otherwise slow, if you do them in python], and are very interesting for funky tensor-stuff

for more info, see //docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html and //docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html

In Python, we can implement a matrix as nested list [list inside a list].

We can treat each element as a row of the matrix.

For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix.

The first row can be selected as X[0]. And, the element in first row, first column can be selected as X[0][0].

Multiplication of two matrices X and Y is defined only if the number of columns in X is equal to the number of rows Y.

If X is a n x m matrix and Y is a m x l matrix then, XY is defined and has the dimension n x l [but YX is not defined]. Here are a couple of ways to implement matrix multiplication in Python.

Source Code: Matrix Multiplication using Nested Loop

# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range[len[X]]:
   # iterate through columns of Y
   for j in range[len[Y[0]]]:
       # iterate through rows of Y
       for k in range[len[Y]]:
           result[i][j] += X[i][k] * Y[k][j]

for r in result:
   print[r]

Output

[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

In this program, we have used nested for loops to iterate through each row and each column. We accumulate the sum of products in the result.

This technique is simple but computationally expensive as we increase the order of the matrix.

For larger matrix operations we recommend optimized software packages like NumPy which is several [in the order of 1000] times faster than the above code.

Source Code: Matrix Multiplication Using Nested List Comprehension

# Program to multiply two matrices using list comprehension

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]

# result is 3x4
result = [[sum[a*b for a,b in zip[X_row,Y_col]] for Y_col in zip[*Y]] for X_row in X]

for r in result:
   print[r]

The output of this program is the same as above. To understand the above code we must first know about built-in function zip[] and unpacking argument list using * operator.

We have used nested list comprehension to iterate through each element in the matrix. The code looks complicated and unreadable at first. But once you get the hang of list comprehensions, you will probably not go back to nested loops.

Matrix multiplication is an operation that takes two matrices as input and produces single matrix by multiplying rows of the first matrix to the column of the second matrix.In matrix multiplication make sure that the number of columns of the first matrix should be equal to the number of rows of the second matrix. 

Example: Multiplication of two matrices by each other of size 3×3. 

Input:matrix1 = [[1, 2, 3],
                 [3, 4, 5],
                 [7, 6, 4]]
      matrix2 = [[5, 2, 6],
                 [5, 6, 7],
                 [7, 6, 4]]

Output : [[36 32 32]
          [70 60 66]
          [93 74 100]]

Methods to multiply two matrices in python 

1.Using explicit for loops: This is a simple technique to multiply matrices but one of the expensive method for larger input data set.In this, we use nested for loops to iterate each row and each column. 

If matrix1 is a n x m matrix and matrix2 is a m x l matrix.

Implementation:

Python3

matrix1 = [[12,7,3],

        [4 ,5,6],

        [7 ,8,9]]

matrix2 = [[5,8,1],

        [6,7,3],

        [4,5,9]]

res = [[0 for x in range[3]] for y in range[3]]

for i in range[len[matrix1]]:

    for j in range[len[matrix2[0]]]:

        for k in range[len[matrix2]]:

            res[i][j] += matrix1[i][k] * matrix2[k][j]

print [res]

Output

[[114, 160, 60], [74, 97, 73], [119, 157, 112]]

In this program, we have used nested for loops for computation of result which will iterate through each row and column of the matrices, at last it will accumulate the sum of product in the result. 

2. Using Numpy : Multiplication using Numpy also know as vectorization which main aim to reduce or remove the explicit use of for loops in the program by which computation becomes faster. 
Numpy is a build in a package in python for array-processing and manipulation.For larger matrix operations we use numpy python package which is 1000 times faster than iterative one method. 
For detail about Numpy please visit the Link

Implementation:

Python3

import numpy as np

mat1 = [[1, 6, 5],[3 ,4, 8],[2, 12, 3]]

mat2 = [[3, 4, 6],[5, 6, 7],[6,56, 7]]

res = np.dot[mat1,mat2]

print[res]

Output: 
 

[[ 63 320  83]
 [ 77 484 102]
 [ 84 248 117]]

Using numpy 

Python3

import numpy as np

mat1 = [[1, 6, 5],[3 ,4, 8],[2, 12, 3]]

mat2 = [[3, 4, 6],[5, 6, 7],[6,56, 7]]

res = mat1 @ mat2

print[res]

Output: 
 

[[ 63 320  83]
 [ 77 484 102]
 [ 84 248 117]]

In the above example we have used dot product and in mathematics the dot product is an algebraic operation that takes two vectors of equal size and returns a single number. The result is calculated by multiplying corresponding entries and adding up those products.

This article is contributed by Dheeraj Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks. 


How do you multiply 2x2 matrices in Python?

Step1: input two matrix. Step 2: nested for loops to iterate through each row and each column. Step 3: take one resultant matrix which is initially contains all 0. Then we multiply each row elements of first matrix with each elements of second matrix, then add all multiplied value.

How do you multiply a 2D list in Python?

Multiply Two Lists in Python Using the numpy. multiply[] Method. The multiply[] method of the NumPy library in Python, takes two arrays/lists as input and returns an array/list after performing element-wise multiplication.

How is matrix multiplication done in Python?

Multiplication can be done using nested loops. Following program has two matrices x and y each with 3 rows and 3 columns. The resultant z matrix will also have 3X3 structure. Element of each row of first matrix is multiplied by corresponding element in column of second matrix.

Can you multiply matrices in Python?

The first row can be selected as X[0] . And, the element in first row, first column can be selected as X[0][0] . Multiplication of two matrices X and Y is defined only if the number of columns in X is equal to the number of rows Y .

Chủ Đề