Azzera filtri
Azzera filtri

How do I store data from my loop?

3 visualizzazioni (ultimi 30 giorni)
Scott Powers
Scott Powers il 29 Set 2017
Commentato: Kian Azami il 2 Ott 2017
I am trying to run a loop to calculate and plot substrate concentration over time. With this, I am having problems storing the values for S1 as the loop runs to plot it later. I also would appreciate if anyone could help code stopping the loop when S1 reaches 0, because S1 should never be negative. Thanks
clear,clc
mumax=1.35;
ks=0.00396;
corg_in=2;
csub_in=20;
Yxs=0.54;
mustart=(mumax*csub_in)/(ks+csub_in);
S1=csub_in
B=300
C=10
d=2*B-51
n=linspace(1,C,B)
g=linspace(1,C,d)
t=0
t2=0
ds_dt=((mumax*S1)/(ks+S1)*exp((mumax*S1)*t/(ks+S1)))/0.54
S1=csub_in-(ds_dt/B) %new substrate level
for i=1:numel(g)
ds_dt=((mumax*S1)./(ks+S1)*exp((mumax*S1).*t./(ks+S1)))./0.54;
S1=S1-(ds_dt./B)
t=t+(1./B);
end
disp(S1);
  3 Commenti
Guillaume
Guillaume il 29 Set 2017
@Kian,
It would be better if your comment was an answer. That way, if Scott is happy with it he can accept it and you get reputations point for it. You get no reputation for comments.
Saying that:
  • Your S2 variable should be preallocated. Resizing a matrix on each iteration of a loop is slow.
  • Do not use return to stop a loop. You stop a for loop with break. return quits the function / stops the script altogether, not executing anything anymore. so your disp(S2) would never be executed if S1 becomes negative. See the prominent note in the documentation.
  • I don't really understand why you added this negative test condition that wasn't present in the original code.
Kian Azami
Kian Azami il 2 Ott 2017
@Guillaume
I noticed how you have defined the for loop. Of course, it is smarter. the same for the use of break and return.
I put the negative test condition to stop the iteration if the value of S1 goes to negative values.
Many thanks for your comments and increasing my awareness.

Accedi per commentare.

Risposte (1)

Guillaume
Guillaume il 29 Set 2017
Modificato: Guillaume il 29 Set 2017
%.. your initialisation code
S1 = zeros(1, numel(g) + 1); %create vector to receive all S1 values needs one more elements than will be generated to accomodate the starting value
S1(1) = csub_in; %put initial value as 1st element
for step = 1:nueml(g)
ds_dt = ... %your formula, replacing S1 by S1(step)
S1(step+1) = S1(step) - ds_dt / B;
end
plot(S1);

Categorie

Scopri di più su Chemistry in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by