Learn: In this article, we will see how to **perform matrix multiplication in python**. This article comprises matrix multiplication program written in python with Sample Input and Sample Output.

Submitted by Abhishek Jain, on October 02, 2017

For **multiplication of two matrices** A and B, the number of columns in A should be equal to the number of rows in B. For getting the elements of the product matrix, we take the i^{th} row of A and k^{th} column of B, multiply them element-wise and take the sum of all these products.

import random m1=input("Enter No. of rows in the first matrix: ") n1=input("Enter No. of columns in the first matrix: ") a = [[random.random() for col in range(n1)] for row in range(m1)] for i in range(m1): for j in range(n1): a[i][j]=input() m2=input ("Enter No. of rows in the second matrix: ") n2=input ("Enter No. of columns in the second matrix: ") b = [[random.random() for col in range(n2)] for row in range(m2)] for i in range(m2): for j in range(n2): b[i][j]=input() c=[[random.random()for col in range(n2)]for row in range(m1)] if (n1==m2): for i in range(m1): for j in range(n2): c[i][j]=0 for k in range(n1): c[i][j]+=a[i][k]*b[k][j] print c[i][j],'\t', print else: print "Multiplication not possible"

Output

Enter No. of rows in the first matrix: 3 Enter No. of columns in the first matrix: 2 1 2 3 4 5 6 Enter No. of rows in the second matrix: 2 Enter No. of columns in the second matrix: 3 1 2 3 4 5 6 Output: 9 12 15 19 26 33 29 40 51

Are you a blogger? Join our Blogging forum.

Comments and Discussions

.resCodeAS1 { display: block; width: 320px; height: 50px; }
@media(min-width: 300px) { .resCodeAS1 { display: none; } }
@media(min-width: 480px) { .resCodeAS1 { display: none; } }
@media(min-width: 750px) { .resCodeAS1 { display: block; width: 336px; height: 280px; } }
(adsbygoogle = window.adsbygoogle || []).push({});

(adsbygoogle = window.adsbygoogle || []).push({});

(adsbygoogle = window.adsbygoogle || []).push({});

solved programs: » C » C++ » DS » Java » C# |

aptitude que. & ans.: » C » C++ » Java » DBMS |

interview que. & ans.: » C » Embedded C » Java » SEO » HR |

Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.

Close