How can I solve the " Index exceeds matrix dimensions" error for the following code ?

1 次查看(过去 30 天)
for v = 2 : 511
for u = 2 : 511
sum = 0;
for i = -2 : 2
for j = -2 : 2
sum = sum + (ID(u, v) * filter(i+3, j+3));
end
end
IDx(u,v) = sum;
end
end

回答(2 个)

Guillaume
Guillaume 2016-10-21
编辑:Guillaume 2016-10-21
"How can I solve the " Index exceeds matrix dimensions" "
Easy, don't index past the matrix dimensions!
Since we have no idea of the size of your variables, it's impossible for us to know which part of the code is at fault. Either ID has less than 511 rows or columns, or filter has less than 5 rows or columns.
Certainly, one way to make sure you don't loop past the dimension of a matrix is not to hardcode these sizes but to ask matlab about them:
for v = 2:size(ID, 2)
for u = 2:size(ID, 1)
%...
for i = 1:size(filter, 1)
for j = 1:size(filter, 2) %did you notice that the outer loops iterate over columns first, but inner loops iterate over rows first?
%...
However, since all you're doing is a convolution, you could just not bother with the loops and simply use conv2:
IDX = conv2(ID, filter, 'valid');
will produce the same result in just on line.
Other thing: don't use sum as a variable name, it's already the name of a very useful matlab function. So is filter. You won't be able to use either if you have variables with the same name.

Thorsten
Thorsten 2016-10-21
Don't use negative indices like -2, they are always invalid. Valid indices in Matlab start with 1 and end with the number of elements along the respective dimension.
But do not use this code, use conv2, as Guillaume pointed out.
  2 个评论
Guillaume
Guillaume 2016-10-21
Well the indices are shifted back to positive integers when actually used for indexing so that's not the issue. Of course, the loops would have been clearer and produced the exact same result, if written:
for i = 1 : 5
for j = 1 : 5
sum = sum + (ID(u, v) * filter(i, j));

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by