Index exceeds array bounds despite a loop to prevent this? (2024)

36 visualizzazioni (ultimi 30 giorni)

Mostra commenti meno recenti

Alexander H il 3 Lug 2024 alle 9:26

  • Link

    Link diretto a questa domanda

    https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this

  • Link

    Link diretto a questa domanda

    https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this

Commentato: Voss il 3 Lug 2024 alle 14:52

Risposta accettata: Voss

Apri in MATLAB Online

function [peak_dat_avg] = FindMuscStrength8chan_Cfs(wavedata,channel,stim_freq,stim_time,lat1,lat2)

artefact_dat = wavedata(:,9,:);

emg_dat = wavedata(:,channel,:);

nframes = size(wavedata,3);

npulse = single(stim_freq*stim_time);

emgpeak_dat = zeros(npulse,1,nframes);

peak_vals = zeros(npulse,1);

for k = 1:nframes

[~, peak_locs] = findpeaks(artefact_dat(:,:,k),'NPeaks',npulse,'MinPeakProminence',0.025,'MaxPeakWidth',5,'MinPeakDistance',700);

start_idx = round(peak_locs + lat1);

end_idx = round(peak_locs + lat2);

numb_peaks = numel(peak_locs);

for i = 1:numb_peaks

for n = 1:numb_peaks

if (start_idx(n) > 6000)

start_idx(n) = 6000;

end_idx(n) = 6000;

end

end

peak_vals(i) = peak2peak(emg_dat(start_idx(i):end_idx(i),:,k));

end

emgpeak_dat(:,:,k) = peak_vals;

end

peak_dat_avg = mean(nonzeros(emgpeak_dat,1));

end

This function is designed to extract a small window of EMG data after locating a stimulation artefact on channel 9 of the data. The issue comes on line 28 where the error 'Index in position 1 exceeds array bounds; Index can't exceed 6000' pops up. I understand this as when trying to select the window of emg_dat it is attempting to start from a sample higher than 6000. However, I tried to implement the if loop above to locate any index values greater than the range of the data and set them to the maximum. I would really appreciate help on fixing this issue

2 Commenti

Mostra NessunoNascondi Nessuno

dpb il 3 Lug 2024 alle 14:19

  • Link

    Link diretto a questo commento

    https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this#comment_3201606

Apri in MATLAB Online

W/o a sample of the data to work with, it's hard to tell what it is you're actually trying to operate on and return which isn't clearly defined here in your explanation.

However, in

for k = 1:nframes

[~, peak_locs] = findpeaks(artefact_dat(:,:,k),'NPeaks',npulse,'MinPeakProminence',0.025,'MaxPeakWidth',5,'MinPeakDistance',700);

start_idx = round(peak_locs + lat1);

end_idx = round(peak_locs + lat2);

numb_peaks = numel(peak_locs);

for i = 1:numb_peaks

for n = 1:numb_peaks

if (start_idx(n) > 6000)

start_idx(n) = 6000;

end_idx(n) = 6000;

end

end

peak_vals(i) = peak2peak(emg_dat(start_idx(i):end_idx(i),:,k));

you first set the entire value of the variables start_idx, end_ix then set an element of an array using index n, then refer to the i element of the array. None of those indexing expressions are consistent with each other and so you're reference to the indices in the selection statement is not using the bounded values you just tried to create.

It would appear that what you need to do instead is to ensure when you create start_idx, end_ix in each pass over the number of frames would be to ensure the end_idx array is no greater than the length of the signal you've passed into findpeaks.

I don't follow the purpose of having the doubly nested loop of i and n, it would seem only the i loop would be sufficient to handle each peak within each frame, but you would need to have the peak_vals array doubley dimensioned over nframesXmax(numbpeaks) to save each peak by frame or use a cell array to store the peak values by frame in an array for each frame.

for k = 1:nframes

trace=artefact_dat(:,:,k);

N=numel(trace);

[~, peak_locs] = findpeaks(trace,'NPeaks',npulse,'MinPeakProminence',0.025,'MaxPeakWidth',5,'MinPeakDistance',700);

start_idx = round(peak_locs + lat1);

end_idx = round(peak_locs + lat2);

end_idx=min(end_idx,N); % ensure don't run over end

...

The above assumes you wouldn't set the value of lat1 such that start_idx would be past the end of the trace, but bounding it similarly would ensure you wouldn't exceed the data length. But, it would appear that if you can't pull a full peak out of the trace, you might want to simply just skip over the last one in a trace in which case testing for index >N and using continue over the loop over number of peaks would just ignore it leaving you with one less artifact. Of course, if lat2 were too large, you could have the case that the starting location for a subsequent artifact/peak could be before the end of the previous; hopefully your screening with findpeaks is eliminating that potential problem.

Attach a data file and somebody is bound to come along and look at it thoroughly...

Alexander H il 3 Lug 2024 alle 14:44

Link diretto a questo commento

https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this#comment_3201636

  • Link

    Link diretto a questo commento

    https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this#comment_3201636

@dpb Thank you very much for the help. The delay values lat1 and lat2 are fixed muscle latencies so they won't change but I've solved the issue by just ensuring both start_idx and end_idx can't exceed the data size as suggested; I've also removed my nested loops which were a silly effort to solve the problem previously.

Accedi per commentare.

Accedi per rispondere a questa domanda.

Risposta accettata

Voss il 3 Lug 2024 alle 14:13

  • Link

    Link diretto a questa risposta

    https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this#answer_1480661

  • Link

    Link diretto a questa risposta

    https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this#answer_1480661

Apri in MATLAB Online

The problem is that some element of end_idx is greater than 6000 but the corresponding element of start_idx is not greater than 6000. In that case, the if condition is not true (because start_idx(n) <= 6000), so the code setting start_idx(n) and end_idx(n) to 6000 doesn't get executed, which leaves end_idx(n) greater than 6000 and causes the error.

Also, there is no need for two nested for loops, checking all n for each i. That's redundant, but it doesn't cause any problems. Fixing that, your code could be written as:

for i = 1:numb_peaks

if (start_idx(i) > 6000)

start_idx(i) = 6000;

end_idx(i) = 6000;

end

peak_vals(i) = peak2peak(emg_dat(start_idx(i):end_idx(i),:,k));

end

Now, to fix the problem outlined above, I assume that in such a case, you'd want only end_idx(i) to be set to 6000, rather than changing both end_idx(i) and start_idx(i), since start_idx(i) is ok (not greater than 6000), in which case you can limit start_idx and end_idx independently:

for i = 1:numb_peaks

if start_idx(i) > 6000

start_idx(i) = 6000;

end

if end_idx(i) > 6000

end_idx(i) = 6000;

end

peak_vals(i) = peak2peak(emg_dat(start_idx(i):end_idx(i),:,k));

end

Another way to do that is using the min function:

for i = 1:numb_peaks

start_idx(i) = min(start_idx(i),6000);

end_idx(i) = min(end_idx(i),6000);

peak_vals(i) = peak2peak(emg_dat(start_idx(i):end_idx(i),:,k));

end

And either of those approaches can be done to all elements at once, before the loop:

start_idx(start_idx > 6000) = 6000;

end_idx(end_idx > 6000) = 6000;

for i = 1:numb_peaks

peak_vals(i) = peak2peak(emg_dat(start_idx(i):end_idx(i),:,k));

end

and:

start_idx = min(start_idx,6000);

end_idx = min(end_idx,6000);

for i = 1:numb_peaks

peak_vals(i) = peak2peak(emg_dat(start_idx(i):end_idx(i),:,k));

end

Finally, for robustness you should avoid hard-coding a value like 6000 in the code. (Consider what might happen if you run this function on an emg_dat that has fewer or more than 6000 rows.) Instead get the actual limit from the data itself:

max_idx = size(emg_dat,1);

and use max_idx in place of 6000 in the code, e.g.:

max_idx = size(emg_dat,1);

start_idx = min(start_idx,max_idx);

end_idx = min(end_idx,max_idx);

for i = 1:numb_peaks

peak_vals(i) = peak2peak(emg_dat(start_idx(i):end_idx(i),:,k));

end

2 Commenti

Mostra NessunoNascondi Nessuno

Alexander H il 3 Lug 2024 alle 14:45

Link diretto a questo commento

https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this#comment_3201646

  • Link

    Link diretto a questo commento

    https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this#comment_3201646

Thanks for all the advice it's really helpful :)

Voss il 3 Lug 2024 alle 14:52

Link diretto a questo commento

https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this#comment_3201651

  • Link

    Link diretto a questo commento

    https://it.mathworks.com/matlabcentral/answers/2134061-index-exceeds-array-bounds-despite-a-loop-to-prevent-this#comment_3201651

You're welcome!

Accedi per commentare.

Più risposte (0)

Accedi per rispondere a questa domanda.

Vedere anche

Categorie

Signal ProcessingSignal Processing ToolboxMeasurements and Feature ExtractionDescriptive Statistics

Scopri di più su Descriptive Statistics in Help Center e File Exchange

Tag

  • error
  • signal processing

Prodotti

  • MATLAB

Release

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Si è verificato un errore

Impossibile completare l'azione a causa delle modifiche apportate alla pagina. Ricarica la pagina per vedere lo stato aggiornato.


Translated by Index exceeds array bounds despite a loop to prevent this? (7)

Index exceeds array bounds despite a loop to prevent this? (8)

Seleziona un sito web

Seleziona un sito web per visualizzare contenuto tradotto dove disponibile e vedere eventi e offerte locali. In base alla tua area geografica, ti consigliamo di selezionare: .

Puoi anche selezionare un sito web dal seguente elenco:

Americhe

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europa

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom(English)

Asia-Pacifico

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本Japanese (日本語)
  • 한국Korean (한국어)

Contatta l’ufficio locale

Index exceeds array bounds despite a loop to prevent this? (2024)

FAQs

What does index exceeds array bounds mean? ›

Index in position 2 exceeds array bounds (must not exceed 1). This is an error that occurs when you are trying to access and element that does not exist. For instance, if I initialize a variable of x to be sized (3,1), then try to extract a value from index (4,4), it will throw this error.

What is array bound exceeded? ›

Diagnostic behavior when S-function writes beyond array bounds assigned in allocated memory.

What does "index exceeds the number of array elements" mean? ›

The error means you are trying to index a vector/array element that does not exist in your variable. Specifically, your error message is telling you your array has a single element, and your index is >1.

How to find the number of elements in an array in Matlab? ›

n = numel( A ) returns the number of elements, n , in array A , equivalent to prod(size(A)) .

How do you avoid an array index out of bounds? ›

Use Proper Validation: Always validate the index before accessing an element in an array or list to ensure it falls within the valid range. Use Enhanced For Loops: When iterating over arrays or collections, consider using enhanced for loops ( for-each loops) to avoid index-related issues.

What happens if an array index goes out of bounds? ›

In this case, it will print the message “Error: Index is out of bounds.” In this example, the variable index is assigned -1 and when we use it to access the element of the array, it will throw an exception because the index is negative and not valid.

How to prevent array out of bounds JavaScript? ›

There are a few ways to fix this, including starting from size-1 and going to i >= 0, or starting from the beginning of the array and executing the for loop from i = 0 to i < size. since you have a index “i”, you check if it is less than “size”, you increment it, and you set arr[i] = i.

What does it mean to overflow an array? ›

If an operation attempts to write to or access an element that is outside the range of the array then this results in a buffer overflow. Buffer overflows can lead to anything from a segmentation fault to a security vulnerability.

What does the array bound signify? ›

Short Answer. Answer: Array bounds checking is a technique used in programming to ensure that memory accesses respect the boundaries or limits of a defined array. It prevents the access of an element outside the valid range of indices, maintaining the safety and integrity of the data stored in the array.

How do you find the maximum index of an array? ›

Recursive Approach to find the maximum of Array:
  1. Set an integer i = 0 to denote the current index being searched.
  2. Check if i is the last index, return arr[i].
  3. Increment i and call the recursive function for the new value of i.
  4. Compare the maximum value returned from the recursion function with arr[i].
Sep 13, 2023

What is the highest index that can be used with an array? ›

The indices allowed fall within a range, typically from 0 to the length of the array minus 1 (for a zero index origin) or 1 to the length of the array (for a 1 index origin). Thus, the highest index is a function of the index origin.

What happens when you index an array? ›

It results in the construction of a new array where each value of the index array selects one row from the array being indexed and the resultant array has the resulting shape (number of index elements, size of row).

How do you find the number of an array? ›

The sizeof() operator in C++ returns the size of the passed variable or data in bytes, plus the total number of bytes required to store an array. So, if we divide the size of the array by the size acquired by each element of the same, we can get the total number of elements present in the array.

How do you count the number of repeated elements in an array? ›

Simple approach

In his approach, we have to traverse through the array using a for loop, and then for each element in the array, we use another array to count any duplicate element on its right. Whenever we find a duplicate element, we increase the count by one and break the inner loop.

How to get element from array in MATLAB? ›

MATLAB Array Indexing

To access elements of a Java® object array, use the MATLAB® array indexing syntax, A(row,column) . In a Java program, the syntax is A[row-1][column-1] .

What is array index out of bounds? ›

The ArrayIndexOutOfBoundsException is a runtime exception in Java that occurs when an array is accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

What does array index out of bounds mean in Outlook? ›

This attachment is no longer in the location it was in when it was added to the template; The attachment has either been moved or deleted. You do not see the attachment in Outlook as Outlook link does not display the attachment if you can't find the file path. Resolution.

What are the bounds of an array? ›

For most arrays, 1 is a convenient lower bound and the number of elements is a convenient upper bound, so you usually don't need to specify both the lower and upper bounds. However, in cases where it is more convenient, you can modify both bounds for any array dimension.

What is the index was outside the bounds of the array problem? ›

The error message "Index was outside the bounds of the array" typically indicates that a program or software is trying to access an element or value from an array using an index that is invalid or out of range. This can occur when the software encounters unexpected data or a programming error.

References

Top Articles
Naloxone, risk reduction knowledge can help keep people safer this summer: Ottawa Public Health
3D-printed Naloxone Trainer unveiled - VA News
Calvert Er Wait Time
I Make $36,000 a Year, How Much House Can I Afford | SoFi
Amc Near My Location
Pieology Nutrition Calculator Mobile
FFXIV Immortal Flames Hunting Log Guide
Mileage To Walmart
Lenscrafters Westchester Mall
Riegler &amp; Partner Holding GmbH auf LinkedIn: Wie schätzen Sie die Entwicklung der Wohnraumschaffung und Bauwirtschaft…
Directions To Lubbock
Katie Boyle Dancer Biography
Erskine Plus Portal
Seth Juszkiewicz Obituary
Gas Station Drive Thru Car Wash Near Me
Craigslist Alabama Montgomery
Dit is hoe de 130 nieuwe dubbele -deckers -treinen voor het land eruit zien
National Office Liquidators Llc
Ostateillustrated Com Message Boards
Spectrum Field Tech Salary
Las 12 mejores subastas de carros en Los Ángeles, California - Gossip Vehiculos
List of all the Castle's Secret Stars - Super Mario 64 Guide - IGN
Traveling Merchants Tack Diablo 4
Indiana Wesleyan Transcripts
Military life insurance and survivor benefits | USAGov
Jobs Hiring Near Me Part Time For 15 Year Olds
Sand Dollar Restaurant Anna Maria Island
Breckiehill Shower Cucumber
Student Portal Stvt
Mta Bus Forums
Astro Seek Asteroid Chart
FREE Houses! All You Have to Do Is Move Them. - CIRCA Old Houses
Wake County Court Records | NorthCarolinaCourtRecords.us
Craigslist Neworleans
THE 10 BEST Yoga Retreats in Konstanz for September 2024
A Man Called Otto Showtimes Near Amc Muncie 12
In Polen und Tschechien droht Hochwasser - Brandenburg beobachtet Lage
Hannibal Mo Craigslist Pets
Shih Tzu dogs for sale in Ireland
2007 Peterbilt 387 Fuse Box Diagram
St Anthony Hospital Crown Point Visiting Hours
Lovely Nails Prices (2024) – Salon Rates
Charli D'amelio Bj
Leland Nc Craigslist
Scythe Banned Combos
De boeken van Val McDermid op volgorde
About us | DELTA Fiber
Deshuesadero El Pulpo
Sj Craigs
Raley Scrubs - Midtown
David Turner Evangelist Net Worth
Www Extramovies Com
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated:

Views: 6470

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.