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

1 次查看(过去 30 天)
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
Peng Li 2020-4-13
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 个评论
Aaron Ridall
Aaron Ridall 2020-4-13
That fixed the first issue. Thanks so much. Now it states that index exceeds the number of array elements?
Peng Li
Peng Li 2020-4-13
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?

请先登录,再进行评论。

更多回答(1 个)

Ameer Hamza
Ameer Hamza 2020-4-13
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 个评论
Dave
Dave 2020-4-13
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 2020-4-14
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Fluid Dynamics 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by