mirror of
https://github.com/sahinakkaya/til.git
synced 2024-11-22 00:29:37 +01:00
TIL: Defining a piecewise function in numpy
This commit is contained in:
parent
18d2bb0585
commit
9eb2f53360
28
python/defining-a-piecewise-function-in-numpy.md
Normal file
28
python/defining-a-piecewise-function-in-numpy.md
Normal file
@ -0,0 +1,28 @@
|
||||
This is how you can define a piecewise function in numpy:
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def piecewise(t):
|
||||
conds = [
|
||||
t <= -1,
|
||||
(-1 < t) & (t <= 1),
|
||||
(1 < t) & (t <= 5),
|
||||
t > 5
|
||||
]
|
||||
funcs = [
|
||||
lambda t: 0,
|
||||
lambda t: t + 1,
|
||||
lambda t: 4 - 2*t,
|
||||
lambda t: 0
|
||||
]
|
||||
return np.piecewise(t, conds, funcs)
|
||||
|
||||
t = np.arange(-2, 6, 0.01)
|
||||
plt.xlabel('t')
|
||||
plt.ylabel('y(t)')
|
||||
plt.plot(t, piecewise(t))
|
||||
plt.show() # or plt.savefig('my_fig.png')
|
||||
```
|
Loading…
Reference in New Issue
Block a user