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

1 回表示 (過去 30 日間)
Aaron Ridall
Aaron Ridall 2020 年 4 月 13 日
コメント済み: Ameer Hamza 2020 年 4 月 14 日
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 Center および File ExchangeFluid Dynamics についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by