for loop store building vector
Show older comments
I want this code to create a vector of pH as it iterates. i.e. pH will keep building with each iteration. The first parts is just calculations to get pH
% Initial conditions
Vinit = 0.1;
MCH3CO2H = 0.5;
pKa = 4.756;
Ka = 10^-pKa;
pKb = -log10(1e-14/Ka);
Kw = 1*10^-14;
Kb = Kw/Ka;
% Initial equilibrium concentrations
CH = max(roots([1 Ka -MCH3CO2H*Ka]));
% Initial number of moles
NCH = CH * Vinit;
NCH3CO2H = MCH3CO2H * Vinit;
% Initial pH
pHinitial = -log10(CH);
% Loop through different volumes
dV = 1e-5;
MNaOH = 0.1;
for k = dV:dV:1
% Still before equivalence point
if k < 0.49999999
aCH3CO2H = NCH3CO2H - (MNaOH * k);
CCH3CO2H = aCH3CO2H / (Vinit + k);
NCH3CO2 = MNaOH * k;
CCH3CO2 = NCH3CO2 / (Vinit + k);
pH = pKa + log10(CCH3CO2 / CCH3CO2H);
else
bCH3CO2H = (MNaOH * k) - NCH3CO2H;
CCH3CO2H = bCH3CO2H / (Vinit + k);
CCH3CO2 = CCH3CO2H.^2 / (Kb);
pH = 14 - (pKb + log10(CCH3CO2H / CCH3CO2));
end
end
Answers (1)
Walter Roberson
on 5 Sep 2013
Before the loop,
J = 0;
First statement inside the loop:
J = J + 1;
Then in the if/else portion, instead of assigning to pH, assign to pH(J)
Note: your code would be much more efficient if vectorized.
Categories
Find more on Clustering in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!