0

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:

  1. Define t to be in the range 0 to 12.
  2. Define the function f(t).
  3. Use the statement, if t is an even integer, so it will consider t=0,2,4,6,8,10,12.
  4. Use the for loop to allow us to define f=1 for each of these integers.
  5. 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?

3
  • Your code is particularly hard to read. And I'm not sure the indentation is correct. Could you try to fix it? Commented Dec 2, 2015 at 9:14
  • So you are trying to plot: 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. Commented Dec 2, 2015 at 10:02
  • matplotlib.pyplot.plot(t,f(t),'b-') but your function return error. Try print f(t) to see the error. Commented Dec 2, 2015 at 10:08

1 Answer 1

1

You could use numpy.repeat to double up elements in your array t, and build the (-1,1) pattern with 1 - 2 * (t%2):

t = np.arange(13)
f = np.repeat(1 - 2 * (t%2), 2)[:-1]
t = np.repeat(t, 2)[1:]

In [6]: t
Out[6]: 
array([ 0,  1,  1,  2,  2,  3,  3,  4,  4,  5,  5,  6,  6,  7,  7,  8,  8,
        9,  9, 10, 10, 11, 11, 12, 12])

In [7]: f
Out[7]: 
array([ 1,  1, -1, -1,  1,  1, -1, -1,  1,  1, -1, -1,  1,  1, -1, -1,  1,
        1, -1, -1,  1,  1, -1, -1, 1])

Perhaps even easier is:

In  [8]: n = 12
In  [9]: t = np.repeat(np.arange(n+1), 2)[1:-1]
In [10]: f = np.array([1,1,-1,-1]*(n//2))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.