0

I'm new at coding but i was wondring why this piece of code isn't working. I get the error: "ValueError: Argument Z must be 2-dimensional."

Can someone help solving my problem? Thx S.B.

from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d

ax = plt.axes(projection= '3d')

def z_function(x,y):
    return m/(4*np.pi*r**3)*(3*m*r**2-m)
x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)
r = x**2+y**2
m = 10

X, Y = np.meshgrid(x,y)
Z = z_function(X,Y)

ax.plot_surface(X,Y,Z)
plt.show()
bad_coder
  • 11,289
  • 20
  • 44
  • 72

1 Answers1

0

The reason your code failed is that you generate r as a 1-D array.

To generate it as a 2-D array, run:

r = x**2 + y[:, np.newaxis]**2

The rest of your code is OK.

Consider also such detail: Your z_function uses neither x nor y. Why did you include these parameters?

Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41
  • Thank you very much. Well I don't really understand meaning of the z_function and why there need to be a np.meshgrid. (i saw it in some code's so i used it as wel) I'm a beginner and will learn on the way. Thank you so much for your answer!! – Stijn Blokkenval Feb 22 '22 at 01:01
  • I also don't know why you used *z_function* written this way. Generally: Just like this is the result, when you use code that you don't understand. – Valdi_Bo Feb 22 '22 at 06:04