HEMS HEMS - 3 months ago 38
Python Question

How to plot odd even square wave using python

I am using the below python codes so as to generates a square wave at one specific position. For Eg: you enter 0, the signal is high1 only between 0 and 1[Odd=High]. You enter 1, the output is high1 only between 1 and 2 [Even = High]. How do you extend the below python codes so as to generate odd or even square wave throughout the time span rather that at a single position. Here I am facing problem with 2*n+1 formula.Could anyone help me in this?

Please refer the image below

import numpy as np
import matplotlib.pyplot as plt

def SquareWave(n):
xmin=0;
xmax=10;

ymin=-2;
ymax=2;

Nx=1000;
offset=1;

x=np.linspace(xmin, xmax, Nx);
y=np.sign(x+n)*offset;

y[(x<n)]=0;
y[(x>n+1)]=0;

plt.plot(x, y);
plt.axis([xmin, xmax, ymin, ymax]);
plt.grid()
plt.show()


Odd Wave

Answer

Don't use ;.

import numpy as np
import matplotlib.pyplot as plt

def SquareWave(n,xmin=0,xmax=10,ymin=-2,Nx=1000,ymax=2,offset=1):

    x=np.sort(np.concatenate([np.arange(xmin, xmax)-1E-6,np.arange(xmin, xmax)+1E-6])) 
    #You can use np.linspace(xmin,xmax,Nx) if you want the intermediate points

    y=np.array(x+n+offset,dtype=int)%2


    plt.plot(x, y)
    plt.axis([xmin, xmax, ymin, ymax])
    plt.grid()
    plt.show()