Index out of bounds error even when there ARE enough elements in array

Illustration
Gabriela - 2021-01-06T09:37:17+00:00
Question: Index out of bounds error even when there ARE enough elements in array

I get the error '??? Attempted to access corr_up(2e+006); index out of bounds because numel(corr_up)=2000001.'   I am looping over a correlated signal looking for threshold cross but continue to get this error. When I attempt to access this element of the array explicitly, 'disp(corr_up(2e+006));` or even 'disp(corr_up(2000000));' , it works without error.   Any ideas into this problem. There seems to be enought elements but still getting index out of bounds. i = 1; threshold = max_up/2; while i < length(corr_up) % <--- error thrown here... while corr_up(i) < threshold i = i + 1; end start_of_ping_upsweep = [start_of_ping_upsweep i]; i = i + 0.03*Fs; % look ahead 3 pulse lengths before searching for threshold cross again. end ... ??? Attempted to access corr_up(2e+006); index out of bounds because numel(corr_up)=2000001. Error in ==> check_if_upchirp_or_downchirp_for_90kwqx at 50 while corr_up(i) < threshold

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

Not true. Inside your while loop you have another while loop
 
 
        while corr_up(i) < threshold
            i = i + 1;
        end
with this loop, i could count up basically forever. At some point, i will be more than the length of corr_up.
 
In general you should NEVER ever use a while loop without a fail safe - a count on the number of iterations. You need to check whether the loop counter is more than the max number of iterations you expect. To fix:
        while i <= length(corr_up) && corr_up(i) < threshold
            i = i + 1;
            if i > length(corr_up)
                break;
            end
        end


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!