1

I'm trying to find a mathematician formula to avoid a counter that increment 1 step by step for any loops (any number for first element, last element and increment).

Example 1 (one for loop):

MIN=first element, MAX=last element and HOP=increment (variable i)

with counter:

c = 1;
for i = MIN:HOP:MAX
    c = c + 1;
end

without counter:

for i = MIN:HOP:MAX
    c = floor((i-MIN)/HOP) + 1;
end

Example 2 (two for loops):

MINi=first element, MAXi=last element and HOPi=increment (variable i)

MINj=first element, MAXj=last element and HOPj=increment (variable j)

with counter:

c = 1;
for i = MINi:HOPi:MAXi
    for j = MINj:HOPj:MAXj
        c = c + 1;
    end
end

without counter:

for i = MINi:HOPi:MAXi
    for j = MINj:HOPj:MAXj
        x = (floor((i-MINi)/HOPi)+1);
        y = (floor((j-MINj)/HOPj)+1);
        c = x*y+(x-(floor((MAXi-MINi)/HOPi)+1))*((floor((MAXj-MINj)/HOPj)+1)-y);
    end
end

Any simplification for c formula with two for loops?

Any formula for find c with k for loops, c(k)?

RobinHood
  • 377
  • 4
  • 20
  • 1
    Might I ask why you want to do this, it will be much more computationally efficient, and more readable to just hold the counter. In any case you can use `sub2ind([(MIN1-MIN1)/HOP1, (MIN2-MIN2)/HOP2, ..., (MINk-MINk)/HOPk], i1, i1, ..., ik);` – pseudoDust Mar 11 '14 at 16:27
  • Mainly, I use it to index into a vector, for this reason I need c be 1, 2, 3,... for all iterations in these loops. I don't undestard min1-min1/hop1 always be 0. – RobinHood Mar 11 '14 at 17:55
  • Suppose to be MAX1-MIN1. Why not just use a counter? – pseudoDust Mar 11 '14 at 18:29
  • I only want to find the relationship between the loop parameters and a linear index to avoid multiples counters. I experiment with sub2ind and it appears to be the solution. Example with two loops:`c2=sub2ind([floor((MAXj-MINj)/HOPj)+1 floor((MAXi-MINi)/HOPi)+1],y,x);`. Thanks a lot. – RobinHood Mar 11 '14 at 21:29
  • You can define: indvalues_i = MINi:HOPi:MAXi; (and similarly for j), then have: for i = 1:length(indvalues_i)... such that i is now your "counter"... – Lazarus Mar 11 '14 at 21:40

0 Answers0