[Python] Ensure correct dimensionality with meshgrid combined with dot product

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

  1. Stack

    Stack Membro Participativo

    I am interested in constructing a heatmap that represents a function of the style Z = f(X,Y). To do this I utilized np.meshgrid() to construct my domain.

    import numpy as np
    import seaborn as sb

    x = np.linspace(-np.pi, np.pi, 100)
    y = np.linspace(-np.pi, np.pi, 100)

    X,Y = np.meshgrid(x,y)
    f_XY = np.cos(X**2 + Y**2)

    ax = sb.heatmap(f_XY)


    This example works well. From my understanding because X and Y have the same dimensions of (100, 100), python can compute f_XY = np.cos(X**2 + Y**2) by just taking every pair of X and Y values, and just computing.

    Now I want to make my function a bit more complicated. I am specifically interested in taking the dot product of every point with the vector [1,1,1], where I also fix the z-component to have value 2pi. Finally, I then take the cosine of the resulting value.

    Mathematically I can write out this equation as f_XY = cos( dot([x,y,2pi], [1,1,1]) ), but im not sure how to express this in python itself. I tried the following:

    f_XY = np.cos( np.dot([X, Y, 2*np.pi], [1,1,1]) )


    This produces the error code ValueError: shapes (3,200,200,1) and (3,) not aligned: 1 (dim 3) != 3 (dim 0).

    I understand why as the dimensions that go into np.dot() are different, but Im not sure how to resolve this issue.

    Continue reading...

Compartilhe esta Página