Index in position 1 is invalid. Array indices must be positive integers or logical values?

2 views (last 30 days)
I have tried to create a filter the two function below: averageFilter and maskaverage but im getting this error
Index in position 1 is invalid. Array indices must be positive integers or logical values.
Error in maskaverage (line 12)
summation = summation + img(sr,z);
Error in af (line 9)
image(i,j) = maskaverage(image,i,j,k);
function img = averageFilter(image, M, N,k)
%sr : starting row, er : ending row, sc : starting column, ec : ending column
sr=ceil(k/2);
er =(M-floor(k/2));
sc=ceil(k/2);
ec=(N-floor(k/2));
for i=sr:1:er
for j= sc:1:ec
image(i,j) = maskaverage(image,i,j,k);
end
end
img=image;
end
function summation = maskaverage(img,i,j,k)
sr = i - floor(k/2);
er = i + floor(k/2);
sc = j - floor(k/2);
ec = j + floor(k/2);
summation = 0;
%traversing spirally
while(sr<er && sc < ec)
%traverse through first row
for z = sc:ec
summation = summation + img(sr,z);
end
sc=sc+1;
%traverse through last row
for z=sr:er
summation = summation + img(z,ec);
end
ec=ec-1;
%traverse through last row from the remaining row
if(sr<er)
for z=ec:sc
summation = summation + img(er,z);
end
sr=sr-1;
end
%print first col from the remaining
if(sc<ec)
for z= er:sr
summation=summation + img(z,sc) ;
end
sc=sc+1;
end
end
summation = summation/(k*k);
end

Answers (1)

Cris LaPierre
Cris LaPierre on 10 Oct 2020
What is the size of img? What is the value of sr in line 12?
summation = summation + img(sr,z);
The error would suggest a problem with the value of sr. In particular, it sounds like sr is either less than 1 or not an integer. We don't have enough information into the various variable values used to ultimately calculate sr to tell you for certain.
  1 Comment
JAPHUNGSHAR BRAHMA
JAPHUNGSHAR BRAHMA on 12 Oct 2020
Yes, there was an error with the code in maskaverage function i.e i incremented 'sc' instead of 'sr' and decremented sr instead of er . Also decremenation step by -1 in z=ec:sc and z= er:sr.
Its works fine now as an average filter. Btw Thanks for your effort.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!