MATLAB 'for' loop skipping IF statement

1.5k views Asked by At
range = min(x):0.0001:max(x);
N = numel(range);
x = sort(x);
hit = 0;
i=1;

for j = 1:(N-1)
    if range(j) <= x(i) && x(i) < range(j+1)
        hit = hit + 1;
        i = i+1;
        if x(i) == x(i-1)
            while x(i) == x(i-1)    % If there are more than one of the same
                hit = hit + 1;      % numbers in succession, this allows x and
                i = i+1;            % hit to carry on incrementing. 
            end %while
        end %if
    end %if
end %for
disp(hit)

This code compares 'range' and 'x'. It checks to see if 'x' is between values in 'range', if so the 'hit' counter gets incremented and so does the current value of 'x'.

Problem is, on some random values of x (as far as I can tell they are random), although they should satisfy the inequality in the 'IF' statement, the 'IF' statement gets ignored, the for loop continues and thus the final 'hit' value is wrong.

'x' is usually a 1D array about a million or so wide.

for this example, let

`x = [-2.1792 -2.1759 -2.1758 -2.1748 -2.1658 -2.1648 -2.1646 -2.1604 -2.1603 -2.1550]`

'hit' should equal '10' but instead outputs '2' since it decides to skip the 'IF' statement at 'j=35'.

To clarify. When 'j=35', range(j) = -2.1758 and i=3 meaning x(i)=-2.1758

I'm pretty sure that:

range(j) <= x(i) && x(i) < range(j+1)
-2.1758 <= -2.1758 && -2.1758 < -2.1757    %**edited, meant -2.1757 not -2.1759**

Is true.

I hope I'm just doing something silly here that I can't see. Sorry if it's a badly formatted question, it's my first here. Cheers in advance.

2

There are 2 answers

5
Ben Jackson On BEST ANSWER

A subsequent number x(i) could pass this test:

if range(j) <= x(i) && x(i) < range(j+1)

Without actually being equal to its neighbor:

    if x(i) == x(i-1)

It could be infinitesimally larger and thus you move to the next j and it is out of range. Your inner while needs the same condition as the outer if. And you can skip the if COND while COND and just do while COND since it will work the same.

1
Floris On

Would the following code not be simpler, faster, and give the same result?

x = sort(x)
hit = sum(diff(x)==0);