MATLAB Troubleshooting Matlab Loops: Discovering a Simple Solution | Get Help Now

  • Thread starter Thread starter mikaili
  • Start date Start date
  • Tags Tags
    Loops Matlab
AI Thread Summary
The discussion centers on a problem encountered in a Matlab loop where the index for an array becomes non-integer due to floating-point representation issues. Specifically, the loop fails when the variable 's' reaches 0.6, as the calculation of 10*s + 1 results in a value like 6.99 instead of 7. This error arises because certain decimal fractions, such as 0.1, cannot be represented exactly in binary, leading to cumulative inaccuracies. The issue highlights the limitations of binary fractions in programming and how they can affect array indexing. Understanding these floating-point representation challenges is crucial for troubleshooting similar issues in Matlab.
mikaili
Messages
3
Reaction score
0
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 anybody please check and let me know the result
 
Physics news on Phys.org
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
 

Similar threads

Replies
1
Views
2K
Replies
4
Views
2K
Replies
4
Views
3K
Replies
6
Views
2K
Replies
5
Views
1K
Replies
4
Views
1K
Back
Top