I have this code in MATLAB and I am trying to convert it in Python.
yc(1:45)=-2;
yc(46:90)=2;
yc(91:136)=-2;
yc(137:182)=2;
I don't know how to convert it in python thnx for helping me
The direct equivalent, using numpy
would be:
>>> import numpy as np
>>> yc = np.empty(182)
>>> yc[:45] = -2 # Equivalent to, yc[0:45] = -2
>>> yc[45:90] = 2
>>> yc[90:136] = -2
>>> yc[136:] = 2 # Equivalent to, yc[136:182] = 2
Where np.empty
creates an array with random values, of given shape. Then we proceed to assign different values by accessing in slices.
You can also try with np.arange
and np.select
:
>>> yc = np.arange(182)
>>> yc = np.select(condlist=[
yc < 45, (45 <= yc) & (yc < 90),
(90 <= yc) & (yc < 136), yc >= 136
],
choicelist=[-2, 2, -2, 2])
>>> yc
array([-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
Here np.arange
creates an array with values ranging from 0 to 181 (182 values in total), and we create a new array substituting different values in the array according to different conditions.
Things to keep in mind:
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.