Home > Back-end >  How can I get the same results in Python is it in the following MATLAB code? how to change this code
How can I get the same results in Python is it in the following MATLAB code? how to change this code

Time:10-09

In short how can I change this 1 line code reshape((b-c)/d,1,[]) into 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

CodePudding user response:

I think you are looking for something as follows:

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])

If you're set on b in the shape as shown in your question, you'll need to transpose twice (which isn't necessary otherwise). I.e.:

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])
  • Related