如何在Python中得到相同的结果是在下面的MATLAB代码中吗?如何将此代码转换为Python?

kr98yfug  于 2022-11-24  发布在  Matlab
关注(0)|答案(1)|浏览(151)

简单地说,我如何将这一行代码reshape((b-c)/d,1,[])转换为python?

>> a=1:20;
>> b=reshape(a,4,5)

b =

     1     5     9    13    17
     2     6    10    14    18
     3     7    11    15    19
     4     8    12    16    20

>> c=-3;
>> d=2;
>> reshape((b-c)/d,1,[])

ans =

  Columns 1 through 17

    2.0000    2.5000    3.0000    3.5000    4.0000    4.5000    5.0000    5.5000    6.0000    6.5000    7.0000    7.5000    8.0000    8.5000    9.0000    9.5000   10.0000

  Columns 18 through 20

   10.5000   11.0000   11.5000
ljsrvy3e

ljsrvy3e1#

我想你正在寻找的东西如下:

import numpy as np

a = np.arange(1,21)
b = a.reshape(5,4)

c = -3
d = 2
ans = ((b-c)/d).flatten()

# array([ 2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ,  5.5,  6. ,  6.5,  7. ,
#         7.5,  8. ,  8.5,  9. ,  9.5, 10. , 10.5, 11. , 11.5])

如果你的问题中所示的形状设置为b,你需要转置两次(否则就不需要转置),即:

a = np.arange(1,21)
b = a.reshape(5,4).transpose()

array([[ 1,  5,  9, 13, 17],
       [ 2,  6, 10, 14, 18],
       [ 3,  7, 11, 15, 19],
       [ 4,  8, 12, 16, 20]])

c = -3
d = 2
ans = ((b-c)/d).transpose().flatten()

# array([ 2. ,  2.5,  3. ,  3.5,  4. ,  4.5,  5. ,  5.5,  6. ,  6.5,  7. ,
#         7.5,  8. ,  8.5,  9. ,  9.5, 10. , 10.5, 11. , 11.5])

相关问题