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

G
Gabriela · Jan 6, 2021 · 2K views
Question
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 PhD Expert
Answered Aug 17, 2026
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
100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!