MATLAB: ??? Index exceeds matrix dimensions.

indexingmatrix

I keep getting this error every time I run this code. Can you tell me where I am wrong? I have run through the debugger and can't seem to figure out where I went wrong.
K = zeros(3*NN,3*NN);
M = zeros(3*NN,3*NN);
for n = 1:NE
i = Dir(n,2);
j = Dir(n,3);
K(3*i-2:3*i,3*i-2:3*i)= K11(:,:,n) + K(3*i-2:3*i,3*i-2:3*i);
K(3*i-2:3*i,3*j-2:3*j)= K12(:,:,n);
K(3*j-2:3*j,3*i-2:3*i)= K21(:,:,n);
K(3*j-2:3*j,3*j-2:3*j)= K22(:,:,n) + K(3*j-2:3*j,3*j-2:3*j);
M(3*i-2:3*i,3*i-2:3*i)= M11(:,:,n) + M(3*i-2:3*i,3*i-2:3*i);
M(3*i-2:3*i,3*j-2:3*j)= M12(:,:,n);
M(3*j-2:3*j,3*i-2:3*i)= M21(:,:,n);
M(3*j-2:3*j,3*j-2:3*j)= M22(:,:,n) + M(3*j-2:3*j,3*j-2:3*j);
end

Best Answer

Use the debugger again:
dbstop if error
Then start the code. Matlab stops when the error occurs and you can evaluate the parts of the currently processed line in the command window, e.g.:
K11(:, :, n)
K(3*i-2:3*i, 3*i-2:3*i)
Then you will find out, which of the statements cause the error. Btw. the responsible line is shown in the error message also, and therefore it is a good idea to post the complete error messages, if you want help in the forum.
Another hint: If you use temporary variables for the index expressions, the code will look cleaner:
a = 3*i-2;
b = 3*i;
c = 3*j-2;
d = 3*j;
Beside the reduction of runtime, the improved readability will allow for an easier debugging.