What is the advantage of linspace over the colon “:” operator?

前端 未结 3 1429
小鲜肉
小鲜肉 2020-11-29 09:06

Is there some advantage of writing

t = linspace(0,20,21)

over

t = 0:1:20

?

I understand the fo

3条回答
  •  生来不讨喜
    2020-11-29 10:05

    linspace and the colon operator do different things.

    linspace creates a vector of integers of the specified length, and then scales it down to the specified interval with a division. In this way it ensures that the output vector is as linearly spaced as possible.

    The colon operator adds increments to the starting point, and subtracts decrements from the end point to reach a middle point. In this way, it ensures that the output vector is as symmetric as possible.

    The two methods thus have different aims, and will often give very slightly different answers, e.g.

    >> a = 0:pi/1000:10*pi;
    >> b = linspace(0,10*pi,10001);
    >> all(a==b)
    ans =
         0
    >> max(a-b)
    ans =
       3.5527e-15
    

    In practice, however, the differences will often have little impact unless you are interested in tiny numerical details. I find linspace more convenient when the number of gaps is easy to express, whereas I find the colon operator more convenient when the increment is easy to express.

    See this MathWorks technical note for more detail on the algorithm behind the colon operator. For more detail on linspace, you can just type edit linspace to see exactly what it does.

提交回复
热议问题