index exceeds matrix dimension in image convolution

function y=convolve(Im,H) %#ok<*STOUT,*INUSD>
In=imread(Im);
I=im2double(In);
[rows,columns]=size(I); %#ok<*NOPRT,*ASGLU>
[rowsx,columnsx]=size(H);
C=0;
a=0;
b=0;
rowsy=rows-rowsx+1;
columnsy=columns-columnsx+1;
c=zeros(rowsy,columnsy);
for k=1:1:rowsy-1
for p=1:1:columnsy-1
for i=1:1:rowsx
for j=1:1:columnsx
T=I(i+a,j+b)*H(i,j);
C=C+T;
end
end
c(k,p)=C;
b=b+1;
end
a=a+1;
end
y=c;
Hi there, I am trying to code a two dimensional matrix convolution. However when I run this code there is an error: Index exceeds matrix dimensions.
Error in convolve (line 17) T=I(i+a,j+b)*H(i,j); But I cannot find where is wrong, can any one help? Thanks.

Answers (1)

You have
I(i+a,j+b)
when i can be up to size(I,1) and j can be up to numels(I)/size(I,1) . Which, incidentally, is only the same as size(I,2) if I is two dimensional, which in turn implies that I is a grayscale image. Using size() the way you did is wrong for images that can be RGB.
Anyhow, suppose that the image is 2D so i can be up to the number of rows, and j can be up to the number of columns. But when i is equal to the number of rows, then i+a will be past the last row unless a is 0 (or negative), and j+b will be past the last column unless b is 0 (or negative.) But you have b=b+1; so b can become 1. When b does become 1, then as soon as j becomes columnsx, then j+1 would be past the end of I
Convolution with an array or vector produces a result that is larger than the original matrix. Have a look at the documentation for conv2() at the 'full' and 'same' and 'valid' options there, which are three different approaches for dealing with the size of output to be returned.

2 Comments

rowsy=rows-rowsx+1;
columnsy=columns-columnsx+1;
c=zeros(rowsy,columnsy);
for k=1:1:rowsy-1
for p=1:1:columnsy-1
for i=1:1:rowsx
for j=1:1:columnsx
T=I(i+a,j+b)*H(i,j);
C=C+T;
I think i,j are for the filter. k,p for the image,so i,j wouldn't change,only a,b change,and I have written rowsy=rows-rowsx+1; columnsy=columns-columnsx+1; so I don't think convolution will produce a result larger than original matix.
At the command line command
dbstop if error
and run again. When it stops, look at i, a, j, b, and size(I) and size(H)

Sign in to comment.

Asked:

on 2 Oct 2016

Commented:

on 2 Oct 2016

Community Treasure Hunt

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

Start Hunting!