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

1 Ansicht (letzte 30 Tage)
Aaron Ridall am 13 Apr. 2020
Kommentiert: Ameer Hamza am 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
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Peng Li am 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.
##### 3 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
Aaron Ridall am 13 Apr. 2020
That fixed the first issue. Thanks so much. Now it states that index exceeds the number of array elements?
Peng Li am 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?

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

Ameer Hamza am 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 KommentareKeine anzeigenKeine ausblenden
Dave am 13 Apr. 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 am 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.

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Matrix Computations finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by