While loop stops interating before end condition is met
显示 更早的评论
Hi all,
I'm facing a weird problem in Matlab R2017b. All I do is checking the difference of some data and iterate as long as this difference meets exactly the initial difference of my data (in this case 0.001). See my simplified code below.
% My data
Data = [0;0.00100000000000000;0.00200000000000000;0.00300000000000000;0.00400000000000000;0.00500000000000000;...
0.00600000000000000;0.00700000000000000;0.00800000000000000;0.00900000000000000;0.0100000000000000;0.0120000000000000];
% The initial difference
Samplingrate = Data(2,1)-Data(1,1);
% Take initial differece as comparison value for while-loop
Diff_XValue = Samplingrate;
% Counter for while-loop/data
counter = 1;
% While-loop
while Diff_XValue == Samplingrate % Check if they are the same
counter = counter + 1;
Diff_XValue = Data(counter + 1,1)-Data(counter,1); % next difference
end
% Failed?
if counter < 11
disp('Failed')
else
disp('Yay')
end
As you can see in data there is always a delta of 0.001, except for counter = 11, so you would expect the while loop to end when counter = 11 is reached. That's not the case here. The while-loop ends at counter = 9. But why? I thought 'maybe it is a numerical issue' and changed my while condition as follows...
while (Diff_XValue < 1.0005*Samplingrate) && (Diff_XValue > 0.9995*Samplingrate)
counter = counter + 1;
Diff_XValue = Data(counter + 1,1)-Data(counter,1);
end
This way everything works fine. Again, but why? Are the decimal zeros a problem to Matlab? But even deleting them doesn't change this behaviour. Any ideas?
Leon
Edit: Yep it's a numerical issue. At counter = 9 Diff_XValue is not exactly 0.001. But I don't get why it's working in the previous iterations...
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!