HEMS - 2 years ago 149

Python Question

I am using the Python codes to generate PWM signal in using vectorization method.But still facing issues.Could anyone help me in this.

`import numpy as np`

import matplotlib.pyplot as plt

percent=input('Enter the percentage:');

TimePeriod=input('Enter the time period:');

Cycles=input('Enter the number of cycles:');

y=1;

x=np.linspace(0,Cycles*TimePeriod,0.01);

t=(percent/100)*TimePeriod;

for n in range(0,Cycles):

y[(n*TimePeriod < x) & (x < n*TimePeriod+t)] = 1;

y[(n*TimePeriod+t < x)& (x < (n+1)*TimePeriod)] = 0;

plt.plot(y)

plt.grid()

end

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

The biggest issue was that you can't assign to y[index] unless y is a vector, but you made it a number. Now there are many ways to do that periodic assignment, I personally like to use the `modulo`

`%`

operator.

```
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
percent=float(raw_input('on percentage:'))
TimePeriod=float(raw_input('time period:'))
Cycles=int(raw_input('number of cycles:'))
dt=0.01 # 0.01 appears to be your time resolution
x=np.arange(0,Cycles*TimePeriod,dt); #linspace's third argument is number of samples, not step
y=np.zeros_like(x) # makes array of zeros of the same length as x
npts=TimePeriod/dt
i=0
while i*dt< Cycles*TimePeriod:
if (i % npts)/npts < percent/100.0:
y[i]=1
i=i+1
plt.plot(x,y,'.-')
plt.ylim([-.1,1.1])
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**