简体   繁体   English

matlab转python编码

[英]matlab to python coding

I have this code in MATLAB and I am trying to convert it in Python.我在 MATLAB 中有这个代码,我正在尝试在 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我不知道如何在 python thnx 中转换它来帮助我

Direct Equivalent直接等效

The direct equivalent, using numpy would be:直接等效,使用numpy将是:

>>> 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.其中np.empty创建一个具有给定形状的随机值的数组。 Then we proceed to assign different values by accessing in slices.然后我们继续通过访问切片来分配不同的值。

Alternate Way替代方式

You can also try with np.arange and np.select :您也可以尝试使用np.arangenp.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.这里np.arange创建了一个值范围从 0 到 181(总共 182 个值)的数组,我们创建一个新数组,根据不同的条件替换数组中的不同值。

Things to keep in mind:要记住的事情:

  • MATLAB starts indexing from 1, whereas python starts from 0. MATLAB 从 1 开始索引,而 python 从 0 开始。
  • You need to pre-allocated an array in order to assign via slices.您需要预先分配一个数组才能通过切片进行分配。

Helpful Links:有用的网址:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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