Why linspace function and Colon (:) operator giving me different number of elements in creating a vector ?
22 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Pushpendra Gupta
le 26 Déc 2021
Commenté : Pushpendra Gupta
le 27 Déc 2021
I am using an Optimization algorithm and the lower and upperbound for time is in between 3.8 seconds to 6 seconds. I wanted to create only 10 element from StartTime to EndTime. Moreover, I wanted to know the successive difference between the element as I will use it later in my function.
StartTime = 3.81;
EndTime = 5.91612005426755; % random number generated from optimization algorithm
tvec = linspace(StartTime, EndTime, 10)
Dtime = tvec(2)-tvec(1)
% If I use Dtime to create the same vector, I am getting only 9 element
% this time.
StartTime:Dtime:EndTime
![Linspace Vs Colon](https://www.mathworks.com/matlabcentral/answers/uploaded_files/844790/Linspace%20Vs%20Colon.png)
0 commentaires
Réponse acceptée
Image Analyst
le 26 Déc 2021
linspace() gives you exactly 10 elements and scales the numbers to make sure that's true.
Colon steps along until the number is more than the ending number and quits without exceeding the ending number. So the 10th number is slightly more than 5.91612005426755 so it quits at 5.6821. So there will be a variable numbers and sometimes a little less than what you expected.
See the FAQ for why sometimes numbers don't add to what you think they should.
3 commentaires
Image Analyst
le 27 Déc 2021
For me, and online, I always get 10 (see below where I ran it from my browser)
StartTime = 3.81;
EndTime = 5.91612005426755; % random number generated from optimization algorithm
tvec = linspace(StartTime, EndTime, 10)
Dtime = tvec(2)-tvec(1)
% If I use Dtime to create the same vector, I am getting only 9 element
% this time.
t2 = StartTime : Dtime : EndTime
I guess if you're still getting 9 elements, you could go a fraction of a Dtime past the end point:
t3 = StartTime : Dtime : (EndTime + 0.1 * Dtime)
Plus de réponses (1)
Matt J
le 26 Déc 2021
Modifié(e) : Matt J
le 27 Déc 2021
The algorithm that linspace uses is,
function out=linspace(a,b,n)
increment=(b-a)/(n-1);
for i=1:n
out(i)=a + increment*(i-1);
end
end
The algorithm that colon uses is,
function out=colon(a,increment,b)
n=floor((b-a)/increment)+1;
out=linspace(a, a+(n-1)*increment, n);
end
In the case of colon, n must be computed from the inputs using floating point arithemtic. In your case, (b-a)/increm=9 in ideal math, but in floating point it can work out to 8.9999999... leading to floor((b-a)/increm)=8. When this happens, n will of course be one fewer than it should be in ideal math.
0 commentaires
Voir également
Catégories
En savoir plus sur Geometry and Mesh dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!