if statement for two arrays
3 views (last 30 days)
I am programming a chemical reaction. I want to make sure that the amount of product produced does not exceed the amount of available reactants (particularly the amount of reactant that is in deficit). dS is the amount of product produced, cA is the concentration of A, cB is the concentration of B, k1 is the rate constant, dt is the time interval for the ith step. Here's what I have so far:
if dS(i+1,:)> cA(i+1,:) | cB(i+1,:);
dS(i+1,:) = min(cA(i+1,:),cB(i+1,:));
The code seems to be producing the correct results. But there are so many rows and columns in each table, it is hard for me to actually check the results in each cell.
The intent of the code is as follows. The first line calculates dS for the ith time step. Then the if statement checks to make sure that the calculated vaule of dS does not exceed the amount of the limiting reactant, which could be either A or B. If it does, the third line of code replaces the values in the cells, where this overcalculation has occurred, with either the value of cA or cB depending upon which one is the reactant in deficit.
Overcalculation is likely because this is an instantaneous reaction between acid and base. I would appreciate it if someone could verify for me that this code matches my intent even if this code is not the most efficient. However, proposals of more efficient code are certainly welcome
Mohammad Sami on 22 Jun 2021
I cannot comment on the chemical engineering side. However assuming that your data have multiple columns and you only want to replace the values in columns where the condition is true, you can do something like this.
cond = dS(i+1,:) > cA(i+1,:) | dS(i+1,:) > cB(i+1,:);
replacement = min(cA(i+1,:),cB(i+1,:));
dS(i+1,cond) = replacement(:,cond);