# index exceed the number of arrays elements

2 visualizaciones (últimos 30 días)
Julio Ferreira el 10 de Ag. de 2022
Comentada: Julio Ferreira el 10 de Ag. de 2022
i have this problem with number of array elements . Index must not exceed 124.
How do i solve this? Thanks
length_collective=length(Collective); %equals to 124
length_single=length(single); %equals to 393
for i=1:1:length(Collective)
aux=[];
for j=1:1:length(single)
if(single(j)>Collective(i) && single(j)<Collective(i+1) )
aux=single(j);
end
if( (single(j)>Collective(length(Collective)-1 )) && i==length(Collective)-1 )
aux=single(j);
end
end
end
##### 0 comentariosMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos

Iniciar sesión para comentar.

Kevin Holly el 10 de Ag. de 2022
Collective = rand(1,124);
single = rand(1,393);
length_collective=length(Collective) %equals to 124
length_collective = 124
length_single=length(single) %equals to 393
length_single = 393
for i=1:1:length(Collective)-1 % I added a minus one here
aux=[];
for j=1:1:length(single)
if(single(j)>Collective(i) && single(j)<Collective(i+1) )% because when i =124, this line tries to read Collective(125), which does not exists (exceeds 124).
aux=single(j);
end
if( (single(j)>Collective(length(Collective)-1 )) && i==length(Collective)-1 )
aux=single(j);
end
end
end
##### 1 comentarioMostrar NingunoOcultar Ninguno
Julio Ferreira el 10 de Ag. de 2022
thank you, it was easier than i tought

Iniciar sesión para comentar.

### Más respuestas (1)

dpb el 10 de Ag. de 2022
length_collective=length(Collective); %equals to 124
length_single=length(single); %equals to 393
for i=1:1:length(Collective)
...
Why compute and save variables of the length and then not use them but call the function again?
NB: As side note, length() is a risky function being as it is defined as max(size()) so that one can get either the number of rows or number columns for a 2D array, depending on its size. It's OK for known 1D vectors; otherwise, use size() with the specific dimension of interest; rarely is the orientation not of importance where length is actually the desired result.
...
aux=[];
for j=1:1:length(single)
if(single(j)>Collective(i) && single(j)<Collective(i+1) )
...
You're running the loop over the total number of elements in the array but then addressing the next element past the one of the loop index -- henc, when you reach the last element, the next one is outside array bounds.
The expedient fix in the loop is to iterate only up to length_single - 1
##### 1 comentarioMostrar NingunoOcultar Ninguno
Julio Ferreira el 10 de Ag. de 2022
thank you, i don't know how i didn't saw it. and thank you for the advice

Iniciar sesión para comentar.

### Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by