Why linspace function and Colon (:) operator giving me different number of elements in creating a vector ?
16 ビュー (過去 30 日間)
古いコメントを表示
Pushpendra Gupta
2021 年 12 月 26 日
コメント済み: Pushpendra Gupta
2021 年 12 月 27 日
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 件のコメント
採用された回答
Image Analyst
2021 年 12 月 26 日
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 件のコメント
Image Analyst
2021 年 12 月 27 日
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)
その他の回答 (1 件)
Matt J
2021 年 12 月 26 日
編集済み: Matt J
2021 年 12 月 27 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!