0

I am trying to perform matrix multiplication in Python using NumPy with the following code:

import numpy as np

A = np.array([[1, 2], [3, 4]])
B = np.array([1, 2, 3])

C = np.dot(A, B)
print("Result", C)

However, I get a ValueError indicating that shapes (2,2) and (3,) are not aligned. What is the problem with my code and how can I fix it so that matrix multiplication works correctly?

1
  • Ey, Frank, bienvenido al sitio. El idioma oficial aquí es el español. ¿Puedes traducir el texto de tu pregunta, por favor?
    – RubioRic
    Commented el 22 abr. a las 12:01

1 respuesta 1

0

The problem lies in the dimensions of matrix B. For matrix multiplication to be possible, the number of columns in the first matrix must be equal to the number of rows in the second matrix. In your case, A is a 2x2 matrix and B is effectively a 1x3 vector. To fix the error, you need to adjust B to be compatible with A. Here are two possible solutions:

  1. If you want B to be a column vector that can be multiplied by A, you must transform B to a 2x1 form:

    import numpy as np

    A = np.array([[1, 2], [3, 4]]) B = np.array([[1], [2]]) # Adjusted to be 2x1

    C = np.dot(A, B) print("result:", C)

  2. If B should be a 2xN array compatible with A, you need to adjust B to be an array with two elements that you can expand as needed:

    import numpy as np

    A = np.array([[1, 2], [3, 4]]) B = np.array([[1, 2], [2, 3]]) # Adjusted to be 2x2

    C = np.dot(A, B) print("result:", C)

Both solutions guarantee that the dimensions of A and B are compatible for multiplication.

1
  • Saludos @AlbertoBurbano, te encuentras en SO en español, por favor traduce tu respuesta para que sea mejor recibida. ;)
    – Israel-ICM
    Commented el 23 abr. a las 13:12

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.