Search code examples
pythonnumpymatrixvectormatrix-multiplication

Multiply sphere parametric equation by a matrix in NumPy, Python


I have a sphere defined in such a way:

sigma, theta = np.mgrid[0:2*np.pi:60j, 0:np.pi:30j]
x = np.cos(sigma) * np.sin(theta)
y = np.sin(sigma) * np.sin(theta)
z = np.cos(theta)

And I am plotting said sphere as below:

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(x, y, z, label='Unit sphere')
plt.show()

This works as expected. However, I need to transform this sphere into an elipsoid by multiplying its parametric equation by a 3x3 matrix, generated as below:

A1 = np.random.uniform(-1,1,(3,3))

Now, from a mathematical point of view, I'm perfectly aware that what I'm looking for is a vertical vector of my x, y and z equations, multiplied in a matrix multiplication (@) with my 3x3 transformation matrix. However, I don't know how to code it in numpy. Thanks in advance.


Solution

  • you can use comprehension loop to multiply the transformation matrix with each set of x,y,z

    original

    enter image description here

    ellipsoid = np.array([np.column_stack((x[i],y[i],z[i])) @ A1 for i in range(60)])
    x_ellipsoid  = ellipsoid [:,:,0]
    y_ellipsoid  = ellipsoid [:,:,1]
    z_ellipsoid  = ellipsoid [:,:,2]
    
    fig = plt.figure()
    ax = plt.axes(projection='3d')
    ax.plot_surface(x_ellipsoid, y_ellipsoid, z_ellipsoid, label='ellipsoid ')
    plt.show()
    

    enter image description here