Matlab: picking only integers out of a for loop

  • MATLAB
  • Thread starter parislad
  • Start date
  • #1
19
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
 

Answers and Replies

  • #2
jhae2.718
Gold Member
1,161
20
Use the floor and ceil functions.
 
  • #3
34,534
6,230
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.
 
  • #4
jhae2.718
Gold Member
1,161
20
Based on mark44's post, I would consider something like this:
Code:
epsilon = 1e-6; [COLOR="SeaGreen"]%or something small[/COLOR]
[COLOR="Blue"]for[/COLOR] i=a:a:b;
    [COLOR="Blue"]if [/COLOR]abs(floor(i)-i) < epsilon;
        [COLOR="SeaGreen"]% commands[/COLOR]
[COLOR="Blue"]    end
end[/COLOR]
 
  • #5
34,534
6,230
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.
 

Related Threads on Matlab: picking only integers out of a for loop

Replies
2
Views
2K
Replies
2
Views
2K
  • Last Post
Replies
3
Views
3K
Replies
1
Views
3K
  • Last Post
Replies
1
Views
645
  • Last Post
Replies
5
Views
3K
  • Last Post
Replies
10
Views
16K
Replies
2
Views
1K
Replies
3
Views
4K
  • Last Post
Replies
3
Views
3K
Top