[Python] How can I improve the efficiency of matrix multiplication in python?

Discussão em 'Python' iniciado por Stack, Maio 24, 2025.

  1. Stack

    Stack Membro Participativo

    I have written a code to do matrix multiplication of different range but it takes a lot of time to execute the code.

    Code:

    # Program to multiply two matrices using nested loops

    import time

    print("Enter the size of matrix A")
    m = int(input())
    n = int(input())
    print("Enter the size of matrix A")
    p = int(input())
    q = int(input())
    if(n==p):
    print('enter matrix A')
    else:
    print("invalid entry")
    exit()
    our_list1 = []
    A = []
    i = 0
    int(i)

    for i in range(m):
    for i in range(n):
    number = int(input('Please enter a element '))
    our_list1.append(number)
    A.append(our_list1)
    our_list1= []
    print(A)
    print('enter matrix B')
    our_list1 = []
    B = []

    for i in range(p):
    for i in range(q):
    number = int(input('Please enter a element '))
    our_list1.append(number)
    B.append(our_list1)
    our_list1= []
    print(B)
    start_time = time.time()

    #
    our_list1 = []
    R = []

    for i in range(m):
    for i in range(q):
    number = 0
    our_list1.append(number)
    R.append(our_list1)
    our_list1= []
    print(R)
    for i in range(len(A)):

    # iterating over column by B
    for j in range(len(B[0])):

    # iterating by rows of B
    for k in range(len(B)):
    R[j] += A[k] * B[k][j]
    print(R)
    print("--- %s seconds ---" % (time.time() - start_time))


    It takes more time to execute this method of matrix multiplication, how can I choose the efficient way of matrix multiplication of huge dimension range? So higher dimension array can be executed smoothly and quickly.

    Sample output:

    Matrix A[[3, 3, 3], [3, 3, 3], [3, 3, 3]]
    Matrix B[[3, 3, 3], [3, 3, 3], [3, 3, 3]]
    [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
    [[27, 27, 27], [27, 27, 27], [27, 27, 27]]
    --- 0.00014400482177734375 seconds ---


    it takes 0.00014400482177734375 seconds can I improve this run time when I do for higher dimension multiplication?

    Continue reading...

Compartilhe esta Página