?? Index exceeds matrix dimensions.

2 views (last 30 days)
Saad Abdullah
Saad Abdullah on 16 Dec 2011
Please can any body tell me whats wrong with my code? Its giving error on the 'If' statement. '??? Index exceeds matrix dimensions.'
function color()
img = imread('peppers.png');
r = img(:,:,1);
g = img(:,:,2);
b = img(:,:,3);
[m n] = size(img);
for i = 1:m
for j = 1:n
if ((r(i,j) - g(i,j)) >= 200) %&& mod(r(i,j) - b(i,j)) >= 200)
im = r(i,j);
else
im = 0;
end
end
end
imshow(im);
  1 Comment
Fangjun Jiang
Fangjun Jiang on 17 Dec 2011
Don't use color as the function name. Strange enough, help color and doc color give me different type of function help.

Sign in to comment.

Answers (1)

Jan
Jan on 16 Dec 2011
img = rand(2,3,4);
[m n] = size(img);
Now m is 2 as expected, but n is 12, the product of all trailing dimensions. Either use:
[m, n, dummy] = size(img);
or
[m, n] = size(r);
The program overwrite im in each iteration. I assume you want to set im(i,j) instead.
A more efficient approach without a loop:
r = img(:, :, 1);
g = img(:, :, 2);
im = r;
im(r - g > 200) = 0;

Community Treasure Hunt

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

Start Hunting!