For loop calcs

6 views (last 30 days)
Matthew Eash
Matthew Eash on 8 Feb 2012
Can anyone explain the issue from the code snippet below? The 8th values in vector x is different (by eps) than the value calculated by the loop...
Just interested, since it is easy to work around.
% ------------
clear;
minx = 1;
maxx = 2;
stepx = .1;
x = minx:stepx:maxx;
k = 0;
z = zeros(size(x));
for y = minx:stepx:maxx
k = k+1;
z(k) = y;
end
plot(x==z)
% -------------------

Answers (3)

Andrei Bobrov
Andrei Bobrov on 8 Feb 2012
instead x==z, use abs(x - z) < 100*eps

Walter Roberson
Walter Roberson on 8 Feb 2012

Matt Tearle
Matt Tearle on 8 Feb 2012
This is truly weird, and the short answer is that I don't know why it's doing that. The values to loop over should be evaluated in the same way as x, as far as I'm aware. I'm guessing that there's some magic going on in the JIT that results in 0.7 being calculated slightly differently, but how or why... I have no idea.
The a:dx:b syntax is actually clever about how it deals with roundoff, in that it doesn't just accumulate values. However, it appears that in the for-loop, it is doing x(k) = a + (k-1)*dx (but vectorized, not as a loop: x(k) = x(k-1) + dx). Weird. Here's an experiment that expands on what you did:
minx = 1;
maxx = 2;
stepx = .1;
x = minx:stepx:maxx;
z1 = zeros(size(x));
z1(1) = minx;
for k = 2:length(z1)
z1(k) = z1(k-1) + stepx;
end
k = 0;
z2 = zeros(size(x));
for y = minx:stepx:maxx
k = k+1;
z2(k) = y;
end
z3 = minx + ((1:length(x))-1)*stepx;
all(x==z1)
all(x==z2)
all(x==z3)
all(z1==z3)
all(z2==z3)
You can see that the for-loop version is giving the same as xmin + dx*(0:n-1), but the simple assignment is being even smarter and giving the rounded values.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!