How can I plot the following function on matplotlib:
For all intervals t in [n,n+1], f(t)=1 for n even and f(t)=-1 for n odd. So this is basically a step function with f(t)=1 from 0 to 1, f(t)=-1 from 1 to 2, f(t)=1 from 2 to 3, f(t)=-1 from 3 to 4, and so on.
This is my code so far:
t = arange(0,12)
def f(t):
if t%2 == 0:
for t in range(t,t+1):
f = 1
if t%2 != 0:
for t in range(t,t+1):
f = -1
This is the process of this code:
- Define t to be in the range 0 to 12.
- Define the function
f(t). - Use the statement, if t is an even integer, so it will consider
t=0,2,4,6,8,10,12. - Use the for loop to allow us to define
f=1for each of these integers. - Repeat for odd values of t.
Can you see anything fundamentally wrong with this code? Am I complicating things?
When I try to plot using
matplotlib.pyplot.plot(t,f,'b-')
matplotlib.pyplot.show()
I get a ValueError saying "x and y must have same first dimension".
What is going wrong here?
t = [0, 1, 1, 2, 2, 3,...] f(t) = [1, 1, -1, -1, 1, 1,...]currently your t is equal to[0,1,2,3,...,12]. You need to have matching x,y pairs which you don't currently have.matplotlib.pyplot.plot(t,f(t),'b-')but your function return error. Tryprint f(t)to see the error.