0

So, my question may not be exactly what is in the title.

I have a function

y = a*x + b

And I want to plot y whith different values of b.

I know that I can do the following:

import numpy as np
import matplotlib.pyplot as plt

a = 2
x = np.array([0,1,2,3,4])
b = 0

for i in range(10):
    y = a*x + b
    b = b+1
    plt.plot(x,y)
 

And that returns exactly what I want.

But, there is someway that I can make this by using b = np.array([0,1,2,3,4,5,6,7,8,9])? So, then my code could look something like:

import numpy as np
import matplotlib.pyplot as plt

a = 2
x = np.array([0,1,2,3,4])
b = np.array([0,1,2,3,4,5,6,7,8,9])

y = a*x + b
plt.plot(x,y)
 

1 Answers1

1

Yes, you can use matrix operations to create a 2D matrix with the result of the operation y = a*x + b.

a = 2
x = np.array([0,1,2,3,4])
b = np.array([0,1,2,3,4,5,6,7,8,9])

y = a*x[:,None]+b
plt.plot(x, y)

enter image description here

EDIT: I'm shwing the solution provided by @Quang Hoang which is much simpler than mine. original code was:

y = np.tile(a*x, (b.size,1)) + b[:,np.newaxis]
plt.plot(x, y.T)
Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75