What is the difference between these two commands?

6 views (last 30 days)
making an array like this x=1:2:10 and like this y=linspace(1,2,10)
  2 Comments
John D'Errico
John D'Errico on 20 Apr 2017
Why not read the help for colon, as well as linspace?
You can learn basic things like this in MATLAB by experimentation. So why not try those two commands, and see what they did?
Dillan Johns
Dillan Johns on 20 Apr 2017
well I know that x= does stuff like startingnumber:increment:finalnumber and y=linspace(startingnumber,finalnumber,#ofintegers) why would i need something like this? in what case would I use one and not the other?

Sign in to comment.

Answers (1)

John D'Errico
John D'Errico on 20 Apr 2017
Edited: John D'Errico on 20 Apr 2017
Ok. You did follow up with a valid question. "Why use one form or the other?"
Because they do different things!
linspace(a,b,n)
generates n equally spaced points between a lower and upper limit.
Colon is different. The colon function is also the colon operator. So...
a:b
or
a:stride:b
Colon uses a stride. Starting from the lower end point, generate points with an indicated stride until you reach the upper end point. The default stride, if none is indicated, is 1.
So sometimes you want points that are spaced with a stride of 0.25, or 1, or 2, whatever. If you know the stride between points, use colon. Note that the end point is NOT guaranteed to be included in the final set.
If you just want a given number of equally spaced points, then use linspace.
Of course, you can always reformulate one problem in the other form. But why bother? While both forms create equally spaced values,there are subtle differences that will be highly important to understand.
Some examples:
1. Suppose I want to do interpolation. I have a set of points in a vector x, sampled at a low frequency. But for a plot, I want to generate a lot of points, then interpolate using some function. So I might use linspace.
Xint = linspace(min(x),max(x),1000);
2. Suppose I need to generate the set of odd integers from 1 to 999, perhaps for a matrix index. Yes, I could figure out how to call linspace here. That would force me to think about how many terms would be in that sequence, to use linspace. While not at all difficult, why bother? Trivial is:
ints = 1:2:999;
Note also that colon here is ABSOLUTELY assured to return integers here, whereas linspace may run into floating point issues. Be careful in assuming when numbers are exact integers. Colon will NEVER cause a problem in that respect.

Tags

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!