0

i am trying to learn the basics of matlab , i wanted to write a mattlab script , in this script i defined a vector x with a "d" step that it's length is (2*pi/1000) and i wanted to plot two sin function according to x : the first sin is with a frequency of 1, and the second sin frequency 10.3 ..

this is what i did:

d=(2*pi/1000);
x=-pi:d:pi;
first=sin(x);
second=sin(10.3*x);
plot(x,first,x,second);

my question: what is the different between :

x=linspace(-pi,pi,1000);

and ..

d=(2*pi/1000);
x=-pi:d:pi;

? i am asking because i got confused since i think they both are the same but i think there is something wrong with my assumption .. also is there is a more sufficient way to write sin function with a giveng frequency ?

jasmin
  • 103
  • 1
  • 3
  • 8
  • 1
    1) there are 1001 points in the `-pi:d:pi` version vs 1000 points for the `linspcae` in your example . 2) they are otherwise identical with small performance differences that you dont care about – bla Apr 03 '18 at 22:48
  • 1
    Possible duplicate of [What is the advantage of linspace over the colon ":" operator?](https://stackoverflow.com/questions/26292695/what-is-the-advantage-of-linspace-over-the-colon-operator) – Cris Luengo Apr 04 '18 at 00:12
  • 1
    You might also be interested in this post: https://stackoverflow.com/q/49377234/7328782 – Cris Luengo Apr 04 '18 at 00:15

1 Answers1

0

The main difference can be summarizes as predefined size vs predefined step. And your example highlights it very well, indeed (1000 elements vs 1001 elements).

The linspace function produces a fixed-length vector (the length being defined by the third input argument, which defaults to 100) whose lower and upper limits are set, respectively, by the first and the second input arguments. The correct step to use is internally computed by the function itself (step = (x2 - x1) / n).

The colon operator defines a vector of elements whose values range between the specified lower and upper limits. The step, which is an optional parameter that defaults to 1, is the discriminant of the vector length. This means that the length of the result is determined by the number of steps that must be accomplished in order to reach the upper limit, starting from the lower one. On an side note, on this MathWorks thread you can find a very interesting discussion concerning the behavior of the colon operator in respect of floating-point management.

Another difference, related to the first one, is that linspace always includes the upper limit value while the colon operator only contains it if the specified step allows it (0:5:14 = [0 5 10]).

As a general rule, I prefer to use the former when I want to produce a vector of a predefined length (pretty obvious, isn't it?), and the latter when I need to create a sequence whose length has only a marginal relevance (or no relevance at all)

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98