# Problem with Matlab LOOPs

• MATLAB

## Main Question or Discussion Point

I have recently found a silly problem with Matlab loop
try the following simple program :
>> clear all
>> for s=0:0.1:1
>> V(10*s+1)=s;
>> end
it will get into trouble when s reaches 0.6

would any body please check and let me know the result

Related MATLAB, Maple, Mathematica, LaTeX News on Phys.org
Mark44
Mentor
I don't have Matlab, so I can't check to see what happens. I suspect that you run into a problem with the index of the array V not being an integer.

If this is the problem you're having, the reason it's happening is that certain numbers that have a nice, neat representation in decimal fractions aren't represented exactly as binary real numbers. One decimal fraction in particular that has this problem is 0.1.

A binary fraction as used in many programming languages uses powers of 1/2. For example, you could think of 3/4 as being represented as .11, meaning 1 * 1/2 + 1 * (1/2)^2. The actual representation is a bit more complicated, but this is the idea.

Just as 1/3 requires an infinite number of decimal places to represent, so does 1/10 as a binary fraction. Since computers don't have an infinite amount of storage available, what you get for the representation of 1/10 in binary is a number that is close, but not exactly correct. The problem gets worse if you add 1/10 to itself a few times, such as what happens in your loop. Apparently, by the time s is .6, the accumulated error is enough so that 10*s + 1 comes out to something like 6.99 or so, instead of 7, and then Matlab complains because you are trying to access an array with an index that isn't an integer.

Thanks Mark44 , Your answer was convincing . Actually when I checked s-fix(s) it was a number in the range of 1*10^-16