Why linspace function and Colon (:) operator giving me different number of elements in creating a vector ?
21 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Pushpendra Gupta
am 26 Dez. 2021
Kommentiert: Pushpendra Gupta
am 27 Dez. 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 Kommentare
Akzeptierte Antwort
Image Analyst
am 26 Dez. 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 Kommentare
Image Analyst
am 27 Dez. 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)
Weitere Antworten (1)
Matt J
am 26 Dez. 2021
Bearbeitet: Matt J
am 27 Dez. 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 Kommentare
Siehe auch
Kategorien
Mehr zu Geometry and Mesh finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!