0

using MATLAB the following code returns a vector starting from -5 to 5 with elements that has 0.01 difference:

x = -5:0.01:5;

what is the equivalent syntax using numpy

yekanchi
  • 813
  • 1
  • 12
  • 30
  • https://numpy.org/doc/stable/reference/generated/numpy.linspace.html#numpy.linspace – user2390182 Dec 29 '20 at 14:17
  • @schwobaseggl `linspace` takes the number of points not the `difference` – yekanchi Dec 29 '20 at 14:24
  • @Yacola The `arange` docs warn against using it with float steps and recommend `linspace`. – user2390182 Dec 29 '20 at 15:06
  • 2
    @yekanchi True, one can directly be calculated form the other, so this shouldn't be a big issue. E.g. `points = int((stop - start) / step) + 1` or sth like tht – user2390182 Dec 29 '20 at 15:10
  • Did you try: `np.arange(-5, 5, .01)`? That's most direct equivalent, though its handling of the end value is different. The similarity between MATLAB's `linspace` and `np.linspace` is closer. – hpaulj Dec 29 '20 at 18:01

2 Answers2

1

This would need an explicit conversion, and probably the intention was to use the limits? - something like:

x = np.linspace(-5,5,int((5-(-5))/.01)+1)

or in general

x = np.linspace(minlimit, maxlimit, int((maxlimit-minlimit)/step)+1)

An alternative is to use numpy arange, and, supposing the range is an exact multiple of the step size, add the step to the second argument of arange:

x = np.arange(-5, 5 + .01, 0.01)

or in general:

x = np.arange(minlimit, maxlimit+step, step)

I am not sure how robust this is against jitter due to limited resolution of floating point values.

Peter
  • 71
  • 4
  • Both these approaches are invariably going to suffer from rounding errors (still, +1). Here are some ideas for how to build a more robust solution: https://stackoverflow.com/questions/49377234/how-does-matlabs-colon-operator-work – Cris Luengo Aug 11 '21 at 15:06
0

based on the comments this was convenient for me:

 x = np.linspace(-5,5,1/0.01)
yekanchi
  • 813
  • 1
  • 12
  • 30