Index exceeds array bounds error in nested for loop

5 vues (au cours des 30 derniers jours)
Swetha Varadharajan
Swetha Varadharajan le 8 Avr 2019
Déplacé(e) : Voss le 3 Jan 2024
Hi,
When I run a script, I get the following error:
"Index exceeds array bounds.
Error in Test1 (line 12)
B{j} = imadd(A{x},A{x+1});"
Both the arrays are of the same dimensions. I am trying to add 2 consecutive images and then fusing the resulting images. Where am I going wrong and how do I fix this?
Here is the code:
N = 8; %Number of Images
i = N - 1; %Number of iterations needed
A = cell(1,N); %Input array of images
B = cell(1,N); %Holds result of added images
Image = imread('1.png');
for z = 1:8
A{z} = imread(sprintf('%d.png',z));
end
if (i~=0)
for x=1:1:i
for j=1:1:(N/2)
B{j} = imadd(A{x},A{x+1});
x = x+2;
end
end
for y=1:1:(N/2)
Image = imfuse(Image,B{y},'blend');
end
else
disp('Error: Minimum of 2 images needed');
end
  1 commentaire
Guillaume
Guillaume le 8 Avr 2019
Ignoring the fact that x goes out of bound indeed as pointed out by Alex Mcaulley, the double for loops doesn't make any sense.
for x = 1:i
for j = 1:N/2
B{j} = something;
end
end
At x=1, you fill B{1:N/2} with some values. At x=2, you overwrite all these values with possibly new ones, etc. At the end, the code is simply equivalent to
x = i; %what badly named variables these are!
for j = N/2
B{j} = something
end

Connectez-vous pour commenter.

Réponse acceptée

Alex Mcaulley
Alex Mcaulley le 8 Avr 2019
Déplacé(e) : Voss le 3 Jan 2024
The length of A is 8. In this loop
for x=1:1:i
for j=1:1:(N/2)
B{j} = imadd(A{x},A{x+1});
x = x+2;
end
end
x is going upper than 8, then gives an error.
  2 commentaires
Swetha Varadharajan
Swetha Varadharajan le 8 Avr 2019
Déplacé(e) : Voss le 3 Jan 2024
Yes, I see it now.
Thanks for your help!
Adam Danz
Adam Danz le 8 Avr 2019
Déplacé(e) : Voss le 3 Jan 2024
@Alex Mcaulley, you could move your comment to the answers section. That way the question appears as answered.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by