How do I store data from my loop?
1 view (last 30 days)
Show older comments
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 Comments
Guillaume
on 29 Sep 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
on 2 Oct 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.
Answers (1)
Guillaume
on 29 Sep 2017
Edited: Guillaume
on 29 Sep 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);
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!