How to implement matrix multiplication by python

Source: Internet
Author: User
In this paper, we describe how to implement matrix multiplication in Python. Share to everyone for your reference. The implementation method is as follows:

def Matrixmul (A, B): res = [[0] * len (b[0]) for I in Range (Len (a))] for I in range (Len (a)): fo R j in Range (Len (b[0)): For K in range (len (B)): res[i][j] + = a[i][k] * B[k][j] return resdef matrixMul2 (A, b  ): return [[[Sum] (A * b for a, b in zip (A, b)) ' for B ' in Zip (*b)] ' for a ' in a]a = [[+], [3,4], [5,6], [7,8]]b = [[1,2,3,4], [5,6,7,8]] Print Matrixmul (A, b) print Matrixmul (b,a) print "-" *90print MatrixMul2 (A, b) print matrixMul2 (b,a) print "-" *90from numpy Import Dotprint Map (List,dot (b)) print map (List,dot (b,a)) #Out: #[[11, 14, 17, 20], [23, 30, 37, 44], [35, 46, 57, 68], [47 , 92]]#[[50, the 140]]#------------------------------------------------------------------------#[[11, and (+), [+], [+], [Max], [Max], [+], [+], [] ----------------------------------------#[[11, 14, 17, 20], [23, 30, 37, 44], [35, 46, 57, 68], [47, 62, 77, 92]]#[[50, 60 ], [[a]] 

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.