For loop calcs

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)
% -------------------

답변 (3개)

Andrei Bobrov
Andrei Bobrov 2012년 2월 8일

0 개 추천

instead x==z, use abs(x - z) < 100*eps
Matt Tearle
Matt Tearle 2012년 2월 8일

0 개 추천

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.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2012년 2월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by