Array indices must be positive integers or logical values error in a loop.

1 view (last 30 days)
Aaron Ridall on 13 Apr 2020
Commented: Ameer Hamza on 14 Apr 2020
I'm working on writing a for loop and I expect that the value the loop will generate is negative, because it represents a decrease in particle concentration over time. However, the loop runs once and then generates the error. My code is below.
w_PS=-0.015;
K= 0.0015; %vertical turbulent diffusivity in m/s
C_PS= 29680; %concentration of particles in a fluid at the start
t= 0; %time
dz=-1;
dt=1;
z=0;
for i=1:365/dt
dC_PSdz = C_PS(i)-(C_PS(i)*w_PS*t(i));
dsink_PSdz = w_PS*C_PS(i)-K*dC_PSdz;
dC_PSdt = dsink_PSdz %dsinkdz = w*C-K*dCdz;
C_PS(i) = C_PS(i-1)+dC_PSdt*dt;
t(i) = t(i-1)+dt;
z(i) = z(i-1)+dz*dt;
end

Peng Li on 13 Apr 2020
I doubt it even could finish once as you are indexing C_PS(0), and t(0), and z(0). Didn't check very carefully but I think if you change for i=1:365/dt to for i = 2:365/dt will work.
Peng Li on 13 Apr 2020
because this time you are indexing C_PS(2) before it actually reaches that size. You'd better figure out what you really need to do. Or give an equation here. You are using the current C_PS to calculate dC_PSdz and are using the previous C_PS to update the current C_PS. is that what you intended to do?

Ameer Hamza on 13 Apr 2020
There are indexing issues in your code
w_PS=-0.015;
K= 0.0015; %vertical turbulent diffusivity in m/s
C_PS= 29680; %concentration of particles in a fluid at the start
t= 0; %time
dz=-1;
dt=1;
z=0;
for i=2:365/dt
dC_PSdz = C_PS(i-1)-(C_PS(i-1)*w_PS*t(i-1)); %<------ see the indexes
dsink_PSdz = w_PS*C_PS(i-1)-K*dC_PSdz; %<------ see the indexes
dC_PSdt = dsink_PSdz %dsinkdz = w*C-K*dCdz;
C_PS(i) = C_PS(i-1)+dC_PSdt*dt;
t(i) = t(i-1)+dt;
z(i) = z(i-1)+dz*dt;
end
2 CommentsShowHide 1 older comment
Ameer Hamza on 14 Apr 2020
Dave, the for loops start from 2, so in the first iteration, you are reading the value C_PS(2-1) = C_PS(1). You cannot read value C_PS(2) at that time because it does not exist.

Categories

Find more on Loops and Conditional Statements 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!

Translated by