简体   繁体   中英

matlab to python coding

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

Direct Equivalent

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.

Alternate Way

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:

  • MATLAB starts indexing from 1, whereas python starts from 0.
  • You need to pre-allocated an array in order to assign via slices.

Helpful Links:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM