I am a beginner at programming, I am using python 3.0
I am given a function h(x) = 1 if 0.1<= x <= 0.3 , or = 0 otherwise
I have
L = 1
N=200
x = numpy.linspace(0,L,N)
I want to define a function for h(x) that loops through the values of x and returns 1 or 0 based on the conditions given above
You can use a list comprehension as following. This is basically using a combination of for loop, if-else statement in a one liner. Here, you use if
condition to check if x
is between 0.1 and 0.3 and saves 1 in the hx
otherwise 0.
import numpy
import matplotlib.pyplot as plt
L = 1
N=200
x = numpy.linspace(0,L,N)
hx = [1 if 0.1 <= i <= 0.3 else 0 for i in x] # list comprehension
plt.plot(x, hx)
plt.xlabel('x', fontsize=18)
plt.ylabel('h(x)', fontsize=18)
Alternative vectorised approach : Here (x>=0.1) & (x<=0.3)
returns the indices where x fulfills the conditions and for those indices, evaluate hx
to 1. Here you initialize hx
to be all zeros.
hx = numpy.zeros(N)
hx[(x>=0.1) & (x<=0.3)] = 1
Using it as a function
def get_hx(x):
# hx = numpy.zeros(N)
# hx[(x>=0.1) & (x<=0.3)] = 1
hx = [1 if 0.1 <= i <= 0.3 else 0 for i in x]
return hx
hx = get_hx(x)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.