0

I am trying to write a function that implements imfilter function. but getting this error.

??? Subscript indices must either be real positive integers or logicals

at this point

s= size(img);

Find below the code snippet

s = size(img);
Ix = zeros(s);
Iy = zeros(s);
for i = 1:s
    for j = 1:s
        temp = img(i-1:i+1,j-1:j+1) .* Gx;
        Ix(i,j) = sum(temp(:));
    end
end

Please is there anything Im doing wrong?

EDITED CODE

s = size(img);
Ix = zeros(s);
Iy = zeros(s);
for i = 2:s(1)-1
    for j = 2:s(2)-1
        temp = img(i-1:i+1,j-1:j+1) .* Gx;
        Ix(i,j) = sum(temp(:));
    end
end
philip
  • 484
  • 9
  • 26
  • For the [generic solution to this problem](http://stackoverflow.com/a/20054048/983722), see [this question](http://stackoverflow.com/q/20054047/983722). – Dennis Jaheruddin May 26 '14 at 15:34

1 Answers1

3

If it genuinely happens at the point of calling s= size(img);, then you probably have a variable size in your workspace which is shadowing the size function.

In addition, there are a couple of possible issues with your loop. First, you can't use zero as in index in MATLAB. Hence, when you have i = 1, j = 1 at the start of your loop, you would expect the temp line to return the Subscript indices error.

the output of size, presuming img is a greyscale image, is going to be two numbers. When you do i = 1:s, it will ignore the second one. This is fine so long as your image is square but will not do what you expect if it isn't.

Finally, have a look at conv2 for cases like this rather than creating a loop.

nkjt
  • 7,825
  • 9
  • 22
  • 28
  • Thanks for the response. But getting another error. >> "Integers can only be combined with integers of the same class, or scalar doubles." I have edited the question to add the edited code – philip May 14 '14 at 13:50
  • Exact as the error says - one of your variables is an integer, one is something other than an integer or a double (probably `Gx`). Please read: http://www.mathworks.co.uk/help/matlab/debugging-code.html – nkjt May 14 '14 at 14:00
  • Try casting your `img` variable to `double` before you go through the loop. – rayryeng May 15 '14 at 11:47