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

1 vue (au cours des 30 derniers jours)
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

Réponse acceptée

Peng Li
Peng Li le 13 Avr 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.
  3 commentaires
Aaron Ridall
Aaron Ridall le 13 Avr 2020
That fixed the first issue. Thanks so much. Now it states that index exceeds the number of array elements?
Peng Li
Peng Li le 13 Avr 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?

Connectez-vous pour commenter.

Plus de réponses (1)

Ameer Hamza
Ameer Hamza le 13 Avr 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 commentaires
Dave
Dave le 13 Avr 2020
Step through your script. What are you trying to do by C_PS(i-1)? As stated above I don't think you are wanting to reduce the index of C_PS by 1.
Ameer Hamza
Ameer Hamza le 14 Avr 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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Fluid Dynamics dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by