Matlab: picking only integers out of a for loop

  • Context: MATLAB 
  • Thread starter Thread starter parislad
  • Start date Start date
  • Tags Tags
    Integers Loop Matlab
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 4K views
parislad
Messages
17
Reaction score
0
Hi, I'm new to this forum and only have a few months experience with MATLAB but am getting to know it. Hope you can help me.

I have a for loop which looks like:

for f = a:a:b
command
end

Now,
I only want to execute this command for the integer values in this loop.
eg. if it was f=0.2:0.2:6.2
I only want to run the code for the integer values f=1,2,3,4,5, and 6.
The problem is a and b are values input by the user, so I'm unsure how to do it.

Any help will be appreciated.
Thanks in advance.
Ben
 
Physics news on Phys.org
Use the floor and ceil functions.
 
jhae2.718's recommendation is good, but it might require a bit of tweaking. Looking at your example, you want "command" to execute when f is 1, 2, 3, 4, 5, and 6. Unfortunately, adding floating point values doesn't work exactly as expected, since the decimal numbers aren't stored in the form you might expect. For example, after the loop runs 5 times f will probably not be exactly 1.0, and I would be willing to bet money that after running 30 times, f will be something other than 6.0.

The reason for this is that certain decimal fractions, especially multiples of 0.2, don't have exact representation as floating point numbers, which are stored as base-16 values. Just as 1/3 doesn't have a finite-length representation as a decimal (i.e., base-10) fraction, fractions such as 1/10 and 1/5 and their multiples don't have finite-length representations as binary floating point numbers. They are stored in a relatively small number of bytes in Matlab (8 bytes, I believe), so the actual value is a little under or a little over the true value. When you add these approximate values repeatedly, the error accumulates.

One way to account for this is to recognize that if the difference of the value of f and the value of floor(f) is small enough, then f is an integer or very close. For "small enough" you could probably use 0.000001.
 
Based on mark44's post, I would consider something like this:
Code:
epsilon = 1e-6; %or something small
for i=a:a:b;
    if abs(floor(i)-i) < epsilon;
        % commands
    end
end
 
I should add that what I described is not specific to Matlab - it's present in any programming languages that work with floating point numbers that are stored in binary form.