Index in Position 2 is invalid.

1 次查看(过去 30 天)
X=[200:2000]
for i = 1:1801
A = X(1,i)/2
B(1,i)= A
end
i=0
while i<1801
if i==750
break
elseif mod(i,2)==1
C(1,i)=B(1,i)*2
elseif mod(i,2)==0
C(1,i)=B(1,i)/2 %Index in Position 2 is invalid.
end
i=i+1
end
The programm works only without the second elseif. If I add the second elseif, I get the error: "Index in Position 2 is invalid." Can someone help?

采纳的回答

Ameer Hamza
Ameer Hamza 2020-5-8
编辑:Ameer Hamza 2020-5-8
In MATLAB, the indexing starts from 1. Therefore you should initialize 'i' with the value of 1
X=[200:2000];
for i = 1:1801
A = X(1,i)/2;
B(1,i)= A;
end
i=1 % <==== initialize with 1
while i<1801
if i==750
break
elseif mod(i,2)==1
C(1,i)=B(1,i)*2;
elseif mod(i,2)==0
C(1,i)=B(1,i)/2 %Index in Position 2 is invalid.
end
i=i+1;
end
Also, note that I have suppressed the output from printing on the command window using semi-colon (;). Printing an array on command window in each iteration is very inefficient. Suppressing the output will result in a speed increase.
  4 个评论
Claudius Simon Appel
Okay, that makes sense so far.
What I don't get is why this is an error that, according to Bhogal, only occurs while the second elseif
if i==750
break
elseif mod(i,2)==1
C(1,i)=B(1,i)*2;
elseif mod(i,2)==0 %% this line here
C(1,i)=B(1,i)/2 %Index in Position 2 is invalid.
end
exists. What is it about this line that prompts matlab to run into an error. Or, to be precise, why does it not run into the same error before?
I know that the original question has been answered, but could someone explain this to me?
Thank you.
Ameer Hamza
Ameer Hamza 2020-5-9
Can you show the code before this if-block? How is B defined?

请先登录,再进行评论。

更多回答(1 个)

Francesco Torricelli
Hi,
you can easily solve your issue by setting i = 1 just before the while loop (i = 0 leads to the error you encountered in the very first iteration).

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by