What is the difference between these two commands?

making an array like this x=1:2:10 and like this y=linspace(1,2,10)

댓글 수: 2

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?
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?

댓글을 달려면 로그인하십시오.

답변 (1개)

John D'Errico
John D'Errico 2017년 4월 20일
편집: John D'Errico 2017년 4월 20일
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.

카테고리

도움말 센터File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

제품

태그

질문:

2017년 4월 20일

편집:

2017년 4월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by