My 'for' loop is giving me "Array indices must be positive integers or logical values. " error.

1 view (last 30 days)
A = [1,3,5,2,7,8];
>> count =0;
>> for i= 1:6
>> count = count + A(i);
Array indices must be positive integers or logical values.
  1 Comment
dpb
dpb on 20 May 2018
A = [1,3,5,2,7,8];
count =0;
for i= 1:6
count = count + A(i); end
>> count
count =
26
>>
Above code didn't generate the error...

Sign in to comment.

Answers (2)

Jan Kubski
Jan Kubski on 21 May 2018
Have you tried to end your for loop with end command? I cannot see it in your code. Probably check this.
A = [1,3,5,2,7,8];
count =0;
for i= 1:6
count = count + A(i);
end

Walter Roberson
Walter Roberson on 21 May 2018
Notice you have
>> for i= 1:6
>> count = count + A(i);
if MATLAB was interpreting the "for i" as a for loop, you would not have received the >> prompt at that point: you would not have any prompt and instead the area below the window would change to "Continue entering statement"
So somehow your "for i" is not being interpreted as being a for statement. Given that, it is probably the case that i is (somehow) not being assigned a value, and so is still the default sqrt(-1) which is not a valid index.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!