Optional Lab-------Gradient Descent

I cannot understand this code:“ax2.plot(1000 + np.arange(len(J_hist[1000:])), J_hist[1000:])”
An integer number can be added with an array?And why the code after the comma is J_hist[1000]?Does J_hist[1000] represent the y axis?
Could anyone else explain it to me?Thanks!

1 Like

Hello Benny @CHEN_Benny,

Operations between a numpy array and a python scalar or another array of different shape are called broadcasting. There are rules to comply with for these operations to be valid, but yes, you can add an integer to an array. To see how broadcasting works, check out this official explanation, and most importantly, try it out yourself such as:

print(np.array([1,2,3]) + 3)

Sometimes the code will be easier to read like this

    1000 + np.arange(len(J_hist[1000:])), 

Now we can see clearly that two arguments are supplied to the method plot, and to find out their meaning, you only need to google for its official doc, which happens to only require us these search keywords “ax plot” and we will find it. Here is the official doc.


Got it !Thanks so much!