Error - Index in position 1 is invalid. Array indices must be positive integers or logical values.
1 次查看(过去 30 天)
显示 更早的评论
I'm relatively new to coding and I was trying to apply a formula to a MATRIX to get relief angle.
Now A is a 10000 x 2 matrix and I want to apply the following formula to it, everytime I try to do so I recieve and Error "Index in position 1 is invalid. Array indices must be positive integers or logical values".
Error in Untitled (line 4)
Y=abs(atan((A(i-1,2)-A(i,2)/2000)));
A=Profiles(:,[1 2]);
for i = 1:10;
Y=abs(atan((A(i-1,2)-A(i,2)/2000)));
i=i+1;
end
0 个评论
采纳的回答
Walter Roberson
2019-12-16
for i = 1:10;
The first time through the loop, i will be assigned the value 1
Y=abs(atan((A(i-1,2)-A(i,2)/2000)));
The first time through the loop, i is 1, so the code would be trying to execute
Y=abs(atan((A(1-1,2)-A(1,2)/2000)));
which is
Y=abs(atan((A(0,2)-A(1,2)/2000)));
However, 0 is not a valid index in MATLAB.
You need to re-think how you calculate the first output.
i=i+1;
You really should have a Very Good Reason why you would alter the loop control variable within a for loop. MATLAB does define what happens, but it is seldom what most people expect would happen.
end
You are not storing the value of Y that you compute. The end result of the for loop is that Y would be the last value that was stored into Y. If you had fixed the i-1 problem, then that would correspond to the i=10 case for the for loop. The calculation for i = 10 has nothing to do with the calculation for i = 9 or i = 8 or so on, so if you are not going to store each of the values as you generate them, then you might as well not run any of those iterations and only run i=10 instead.
You should probably be considering assigning to Y(i) instead of to Y
0 个评论
更多回答(1 个)
Jakob B. Nielsen
2019-12-16
The answer lies in the error - array indeces must be positive integers or logical values. That means you have an issue where its not.
You have this line:
for i = 1:10;
Y=abs(atan((A(i-1,2)-A(i,2)/2000)));
end
The first run will have i=1. That gives:
Y=abs(atan((A(1-1,2)-A(1,2)/2000)));
So you try to call A(0,2). What is the 0th row in a matrix? It doesnt exist, hence the error :)
You probably want to try to run your loop for i=2:10 instead.
0 个评论
另请参阅
类别
在 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!