integers error in matlab

i keep getting this error in matlab
this equation is in a for loop
Array indices must be positive integers or logical values.
n= (( 4.6 / 2 ) / 0.1 ) + 1
for i = 1 : n
k( i ) = (4 * x ( i )*( x ( i ) / 2 ))-( R_2b * x ( i ));

1 Comment

post the full code , you seem to be riddling the readers

Sign in to comment.

Answers (2)

Adam Danz
Adam Danz on 13 Mar 2019
Edited: Adam Danz on 13 Mar 2019
The 3 lines of code you presented are fine. My guess is that you're executing the 3rd line manually, perhaps from the command window, before 'i' is defined. When 'i' is not defined, matlab uses 'i' to represent the imaginary number 0 + 1i. This cannot be used as an index value. To test that I'm correct, define i=1 and then run the 3rd line of code manually. If my hunch is correct, the error doesn't happen when the code is executed naturally from the script/function.
Here's a reproduction of the error
clear all
x = [1 2 3 4 5];
x(i)
%<error>
% Array indices must be positive integers or logical values.
i
%ans =
% 0 + 1i

3 Comments

True but OP has defined i right?
Adam Danz
Adam Danz on 13 Mar 2019
Edited: Adam Danz on 25 Mar 2019
Yes, but my hunch is that the line within the for-loop was exected manually from the command window prior to defining 'i'. I sometimes make this mistake when troubleshooting.
Yes seems plausible.

Sign in to comment.

n= (( 4.6 / 2 ) / 0.1 ) + 1
In theory, n is an integer value, specifically 24.
In practice, because neither 4.6 nor 0.1 are exactly representable as double precision numbers, it isn't. It's very, very close but it's not exactly an integer value.
>> n-24
ans =
-3.5527136788005e-15
You can round n so it's exactly an integer value and use that in your for loop.
>> rn = round(n);
>> rn-24
ans =
0
Alternately if you're trying to compute the number of elements the x variable should have, don't. Ask the variable how many elements it has.
n = numel(x)
Depending on whether or not what you've shown is the entire loop body, there may be ways to vectorize the loop and eliminate it entirely.

2 Comments

Adam Danz
Adam Danz on 13 Mar 2019
Edited: Adam Danz on 13 Mar 2019
Super good point! However, that's not what's causing the error "Array indices must be positive integers or logical values." It merely only computes 23 of the 24 iterations.
n= (( 4.6 / 2 ) / 0.1 ) + 1
x= 1:24;
R_2b = 1;
for i = 1 : n
k( i ) = (4 * x ( i )*( x ( i ) / 2 ))-( R_2b * x ( i ));
end
length(k)
%ans = 23 (should be 24 if n were an integer)
You're right, I was too focused on the floating-point issue. Because n is just smaller than 24 the expression 1:n is the same as 1:23.

Sign in to comment.

Categories

Asked:

on 13 Mar 2019

Edited:

on 25 Mar 2019

Community Treasure Hunt

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

Start Hunting!