16

I was wondering what is better style / more efficient:

x = linspace(-1, 1, 100);

or

x = -1:0.01:1;
Samuel
  • 18,286
  • 18
  • 52
  • 88

3 Answers3

18

As Oli Charlesworth mentioned, in linspace you divide the interval [a,b] into N points, whereas with the : form, you step-out from a with a specified step size (default 1) till you reach b.

One thing to keep in mind is that linspace always includes the end points, whereas, : form will include the second end-point, only if your step size is such that it falls on it at the last step else, it will fall short. Example:

0:3:10

ans = 

     0     3     6     9

That said, when I use the two approaches depends on what I need to do. If all I need to do is sample an interval with a fixed number of points (and I don't care about the step-size), I use linspace.

In many cases, I don't care if it doesn't fall on the last point, e.g., when working with polar co-ordinates, I don't need the last point, as 2*pi is the same as 0. There, I use 0:0.01:2*pi.

abcd
  • 41,765
  • 7
  • 81
  • 98
  • linspace in Python has the option to include the endpoint or not. No equivalent in Matlab? – endolith Jul 08 '11 at 17:18
  • This description of the colon operator `:` is not entirely accurate. See [this question](https://stackoverflow.com/q/49377234/7328782) for a detailed description. – Cris Luengo Mar 20 '18 at 19:36
12

As always, use the one that best suits your purposes, and that best expresses your intentions. So use linspace when you know the number of points; use : when you know the spacing.

[Incidentally, your two examples are not equivalent; the second one will give you 201 points.]

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
6

As Oli already pointed out, it's usually easiest to use linspace when you know the number of points you want and the colon operator when you know the spacing you want between elements.

However, it should be noted that the two will often not give you exactly the same results. As noted here and here, the two approaches use slightly different methods to calculate the vector elements (here's an archived description of how the colon operator works). That's why these two vectors aren't equal:

>> a = 0:0.1:1;
>> b = linspace(0,1,11);
>> a-b

ans =

  1.0e-016 *

  Columns 1 through 8

         0         0         0    0.5551         0         0         0         0

  Columns 9 through 11

         0         0         0

This is a typical side-effect of how floating-point numbers are represented. Certain numbers can't be exactly represented (like 0.1) and performing the same calculation in different ways (i.e. changing the order of mathematical operations) can lead to ever so slightly different results, as shown in the above example. These differences are usually on the order of the floating-point precision, and can often be ignored, but you should always be aware that they exist.

gnovice
  • 125,304
  • 15
  • 256
  • 359