Saltar al contenido principal
LibreTexts Español

12.3: Multiplicar Matriz

  • Page ID
    115219
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    #some libraries (maybe not all) you will need in this notebook
    %matplotlib inline
    import matplotlib.pylab as plt
    import numpy as np
    import sympy as sym
    sym.init_printing(use_unicode=True)
    
    import random
    import time
    Hacer esto

    Escribe tu propia función de multiplicación matricial usando la plantilla de abajo y compárela con la multiplicación matricial incorporada que se puede encontrar en numpy. Tu función debe tomar dos “listas de listas” como entradas y devolver el resultado como una tercera lista de listas.

    def multiply(m1,m2):
        #first matrix is nxd in size
        #second matrix is dxm in size
        n = len(m1) 
        d = len(m2)
        m = len(m2[0])
        
        #check to make sure sizes match
        if len(m1[0]) != d:
            print("ERROR - inner dimentions not equal")
        
        #### put your matrix multiply code here #####
        
        return result

    Prueba tu código con los siguientes ejemplos

    #Basic test 1
    n = 3
    d = 2
    m = 4
    
    #generate two random lists of lists.
    matrix1 = [[random.random() for i in range(d)] for j in range(n)]
    matrix2 = [[random.random() for i in range(m)] for j in range(d)]
    sym.init_printing(use_unicode=True) # Trick to make matrixes look nice in jupyter
    
    sym.Matrix(matrix1) # Show matrix using sympy
    sym.Matrix(matrix2) # Show matrix using sympy
    #Compare to numpy result
    np_x = np.matrix(matrix1)*np.matrix(matrix2)
    
    #use allclose function to see if they are numrically "close enough"
    print(np.allclose(x, np_x))
    
    #Result should be True
    #Test identity matrix
    n = 4
    
    # Make a Ransom Matrix
    matrix1 = [[random.random() for i in range(n)] for j in range(n)]
    sym.Matrix(matrix1) # Show matrix using sympy
    #generate a 3x3 identity matrix
    matrix2 = [[0 for i in range(n)] for j in range(n)]
    for i in range(n):
        matrix2[i][i] = 1
    sym.Matrix(matrix2) # Show matrix using sympy
    result = multiply(matrix1, matrix2)
    
    #Verify results are the same as the original
    np.allclose(matrix1, result)

    Estudio de cronometraje

    En esta parte, compararás tu multiplicación matricial con la multiplicación de matriz numpy. Multiplicará dos\(n \times n\) matrices generadas aleatoriamente usando tanto la función multiplicar () definida anteriormente como la multiplicación de la matriz numpy. Aquí está la estructura básica de su estudio de cronometraje:

    1. Inicializar dos listas vacías llamadas my_time y numpy_time
    2. Bucle sobre valores de n (100, 200, 300, 400, 500)
    3. Para cada valor de\(n\) usar la función time.clock () para calcular el tiempo que lleva usar su algoritmo y anexar ese tiempo (en segundos) a la lista my_time.
    4. Para cada valor de\(n\) usar la función time.clock () para calcular el tiempo que se tarda en usar la multiplicación de la matriz numpy y anexar ese tiempo (en segundos) a la lista numpy_time.
    5. Usa el código proporcionado para generar un diagrama de dispersión de tus resultados.
    n_list = [100, 200, 300, 400, 500]
    my_time = []
    numpy_time = []
    # RUN AT YOUR OWN RISK.
    # THIS MAY TAKE A WHILE!!!!
    
    for n in n_list:
        print(f"Measureing time it takes to multiply matrixes of size {n}")
        #Generate random nxn array of two lists
        matrix1 = [[random.random() for i in range(n)] for j in range(n)]
        matrix2 = [[random.random() for i in range(n)] for j in range(n)]
        start = time.time()
        x = multiply(matrix1, matrix2)
        stop = time.time()
        my_time.append(stop - start)
        
        #Convert the lists to a numpy matrix
        npm1 = np.matrix(matrix1)
        npm2 = np.matrix(matrix2)
    
        #Calculate the time it takes to run the numpy matrix. 
        start = time.time()
        answer = npm1*npm2
        stop = time.time()
        numpy_time.append(stop - start)
    plt.scatter(n_list,my_time, color='red', label = 'my time')
    plt.scatter(n_list,numpy_time, color='green', label='numpy time')
    
    plt.xlabel('Size of $n x n$ matrix');
    plt.ylabel('time (seconds)')
    plt.legend();

    Con base en los resultados anteriores, puedes ver que el algoritmo numpy no solo es más rápido sino que también “escala” a un ritmo más lento que tu algoritmo.

    Pregunta

    ¿Por qué crees que la multiplicación de la matriz numpy es mucho más rápida?


    This page titled 12.3: Multiplicar Matriz is shared under a CC BY-NC 4.0 license and was authored, remixed, and/or curated by Dirk Colbry via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.