[Python] Can I multiply these Numpy arrays without creating an intermediary array?

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    This script:

    import numpy as np

    a = np.linspace(-2.5, 2.5, 6, endpoint=True)
    b = np.vstack((a, a)).T
    c = np.array([2, 1])
    print(b*c)


    produces:

    [[-5. -2.5]
    [-3. -1.5]
    [-1. -0.5]
    [ 1. 0.5]
    [ 3. 1.5]
    [ 5. 2.5]]


    which is my desired output. Can it be produced directly with from a and c? Trying a*c and c*a fails due to ValueError: operands could not be broadcast together error. Trying different dimensions of c, e.g. [[2, 1]] fails, too.


    I found that the simplest way to go is to define a differently, i.e. a = np.linspace([-2.5, -2.5], [2.5, 2.5], 6, endpoint=True). I can now write a*c, a*(2, 1), etc. Since it changes my initial post, all answers below remain valid.

    Continue reading...

Compartilhe esta Página