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

採用された回答

Walter Roberson
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

その他の回答 (1 件)

Jakob B. Nielsen
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.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by