Index exceeds matrix dimensions error
2 次查看(过去 30 天)
显示 更早的评论
Hey,
I have written a function (shown below) which acts on a matrix. The matrix is of size 1 x n (I have tried to debug the program by testing the k(n)th number. However, during my loop I get the error that "Index exceeds matrix dimensions." which refers to the line of algebra (sum = sum + ....). I have been trying to debug for a while with no success .. Could anyone please shed some light on my error ?
Thanks for your time.
function [sum]=summation_star(c, d1, d2, d3, d4, k1, k2, k3, w, x, t, n, B)
%coefficients A*inc, Ai* and Bi*
g=9.81;
syms z
sum = 0;
l=1;
while (l < n)
h=1;
while (h < n)
sum = sum + ((mtimes(c,k1(h)*g*exp(i*k1(h)*(x+(B/2)))*exp(-i*w*t)/(w*cosh(k1(h)*d1)))*int(cosh(k2(h)*(z+d2))*cosh(k3(l)*(z+d3)), z, 0, -d4)));
h = h+1;
end
l = l+1;
end
1 个评论
Preethi
2017-1-18
hi,
try by placing a breakpoint at the mentioned step. On execution, once the break point is reached check individual values in the expression. This should help to identify the error source.
回答(1 个)
Guillaume
2017-1-18
I would recommend breaking that expression into smaller parts, using temporary variables. I certainly can't keep track of the opening and closing brackets so I find it very difficult to know what is multiplied with what. At the same time, it'll make it easier to find which part of the expression causes the invalid indexing.
I find it very suspicious that you're using mtimes in lieu of * for one of the multiplications. Why is that particular multiplication singled out?
If n is supposed to be the number of elements in k1 and k2 then it shouldn't be an input but should be derived from k1 or k2 instead:
n = min(numel(k1), numel(k2)); %for example
If n is independent of the number of elements in k1 and k2 then the function ought to check that it is not greater than this number of elements. So I'd start the function with:
validateattributes(n, {'numeric'}, {'scalar', 'integer', positive', '<', min(numel(k1), numel(k2))}
Finally, it's not recommend to use sum as a variable name since it shadows the sum function.
2 个评论
Guillaume
2017-1-18
dbstop if error
Run your code. When it breaks into the debugger, look at the value of n and compare it to:
numel(k1)
numel(k2)
Also, if you've broken down your expression into smaller expression, which subexpression is causing the error?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!