I tried to plot the Dirac Delta rectangular function in Python 2.7 code such that:
enter image description here
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
def ddf(x,sig):
    if -(1/(2*sig))<=x and x<=(1/(2*sig)):
        val=sig
    else:
        val=0
    return val
X=np.linspace(-5,5,1000)
for sig in np.arange(1,5,0.1):
    plt.cla()
    plt.grid()
    plt.title('Dirac Delta function',size=20)
    plt.xlabel('X values',size=10)
    plt.ylabel("Dirac Delta functions' values",size=10)
    plt.ylim(0,1)
    plt.plot(X,ddf(X,sig),color='black')
    plt.pause(0.5)
plt.show()
But when I ran the code it gave the error:
Traceback (most recent call last):
  File "c:/Users/Shubhadeep/Desktop/dff.py", line 22, in <module>
    plt.plot(X,ddf(X,sig),color='black')
  File "c:/Users/Shubhadeep/Desktop/dff.py", line 7, in ddf
    if -(1/(2*sig))<=x and x<=(1/(2*sig)):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Can anyone solve this?
As the error states, you cannot compare single number to an array. Here is a solution for it:
def ddf(x,sig):
    val = np.zeros_like(x)
    val[(-(1/(2*sig))<=x) & (x<=(1/(2*sig)))] = 1
    return val
output sample:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With