if statement for two arrays
4 views (last 30 days)
Show older comments
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:
dS(i+1,:)=k1*cA(i+1,:).*cB(i+1,:)*dt;
if dS(i+1,:)> cA(i+1,:) | cB(i+1,:);
dS(i+1,:) = min(cA(i+1,:),cB(i+1,:));
end
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
1 Comment
Mohammad Sami
on 22 Jun 2021
Your if statement may not do what you intended to do if the condition that you used is an array and not a scalar value.
Answers (1)
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,:);
if any(cond)
replacement = min(cA(i+1,:),cB(i+1,:));
dS(i+1,cond) = replacement(:,cond);
end
2 Comments
Mohammad Sami
on 22 Jun 2021
You have to take into consideration that you are comparing an array not a scalar value.
if [2 0 0 0 2] > [1 0 0 0 1]
disp true;
else
disp false;
end
See Also
Categories
Find more on Reaction Engineering 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!