0

How can I transform the command below from Matlab to Python?

K = 25;         % # points.
    
y0min = 0.1;
    
y0max = 3;
    
y0 = [y0min:(y0max-y0min)./(K-1):y0max]';
Tonechas
  • 11,520
  • 14
  • 37
  • 68
M. Rossi
  • 29
  • 4
  • Welcome to Stack Overflow! Please take the [tour], read [what's on-topic here](/help/on-topic), [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953), and provide a [mre]. "Implement this feature for me" is off-topic for this site. You have to _make an honest attempt_, and then ask a _specific question_ about your algorithm or technique. – Pranav Hosangadi May 14 '21 at 20:52
  • Does this answer your question? [How to use a decimal range() step value?](https://stackoverflow.com/questions/477486/how-to-use-a-decimal-range-step-value) – Pranav Hosangadi May 14 '21 at 20:53

1 Answers1

1

A list comprehension will do the trick:

In [7]: K = 25

In [8]: y0min = 0.1

In [9]: y0max = 3

In [10]: dy = (y0max - y0min)/(K - 1)

In [11]: [y0min + i*dy for i in range(K)]
Out[11]: 
[0.1,
 0.22083333333333333,
 0.3416666666666667,
 0.4625,
 0.5833333333333334,
 0.7041666666666666,
 0.825,
 0.9458333333333333,
 1.0666666666666667,
 1.1875,
 1.3083333333333333,
 1.4291666666666667,
 1.55,
 1.6708333333333334,
 1.7916666666666667,
 1.9125,
 2.033333333333333,
 2.154166666666667,
 2.275,
 2.3958333333333335,
 2.5166666666666666,
 2.6375,
 2.7583333333333333,
 2.879166666666667,
 3.0]

If you are allowed to use NumPy, linspace() is your friend:

In [12]: import numpy as np

In [13]: np.linspace(y0min, y0max, K)
Out[13]: 
array([0.1       , 0.22083333, 0.34166667, 0.4625    , 0.58333333,
       0.70416667, 0.825     , 0.94583333, 1.06666667, 1.1875    ,
       1.30833333, 1.42916667, 1.55      , 1.67083333, 1.79166667,
       1.9125    , 2.03333333, 2.15416667, 2.275     , 2.39583333,
       2.51666667, 2.6375    , 2.75833333, 2.87916667, 3.        ])
Tonechas
  • 11,520
  • 14
  • 37
  • 68
  • Is it possible to transform this vector y_0, created with linspace, into a column vector (Kx1)? In the matlab code above there is a transpose symbol (') (From 1x k to k x 1). – M. Rossi May 15 '21 at 22:53
  • 1
    Try this: `y0 = np.linspace(y0min, y0max, K)[:, None]` – Tonechas May 15 '21 at 22:58