Why am I getting this error? "Array indices must be positive integers or logical values".

6 views (last 30 days)
I am getting the error "Array indices must be positive integers or logical values" when I run the code below. It says the error is in the line that I have bolded.
L_SEC0 = 239;
P0 = 1060;
stiff = 440;
L_CC0 = 122;
t_rise = 120;
t_fall = 60;
C0 = 6.25;
a = 400;
b = 150;
L_total = L_SEC0 + L_CC0;
duration = 0.2;
fs = 10,000;
t_step = 1/fs;
time = 0:t_step:duration;
points = duration*fs;
P_twitch_short = zeros(points,1);
P_twitch_long = zeros(points,1);
P_tetanus = zeros(points,1);
SA = zeros(points,1);
L_CC = L_CC0;
for i = 1:length(time)
P_twitch_short(i) = P0(0.0258*(exp((stiff*RLS)))-0.0258);

Accepted Answer

Voss on 27 Nov 2022
On that line, everything inside the outermost parentheses on the right-hand side is an index into P0:
P_twitch_short(i) = P0(0.0258*(exp((stiff*RLS)))-0.0258);
% ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ index into P0
If that expression, 0.0258*(exp((stiff*RLS)))-0.0258, is not a positive integer, you get the error you got.
Maybe you meant to multiply that by P0 instead of indexing into P0?
P_twitch_short(i) = P0*(0.0258*(exp((stiff*RLS)))-0.0258);
% ^ multiplication

More Answers (1)

John D'Errico
John D'Errico on 27 Nov 2022
Edited: John D'Errico on 27 Nov 2022
Is P0 a function? (NO. It is a scalar variable.)
You have this:
P_twitch_short(i) = P0(0.0258*(exp((stiff*RLS)))-0.0258);
Did you intend to multiply by P0? Does MATLAB allow implicit multiplication, where you don't need to use an operator?
What will happen then you write
instead of
Any guesses? The point is, MATLAB thinks either you must be calling a function named P0 at that point, OR you are trying to index the variable P0. But since it knows that P0 is a variable, it then tries to use what is inside the parens as an index for that variable. And so when that fails, MATLAB gets upset, and returns an error.


Find more on Matrices and Arrays 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!