if statement for two arrays

1 次查看(过去 30 天)
Robert Demyanovich
Robert Demyanovich 2021-6-21
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 个评论
Mohammad Sami
Mohammad Sami 2021-6-22
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.

请先登录,再进行评论。

回答(1 个)

Mohammad Sami
Mohammad Sami 2021-6-22
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 个评论
Robert Demyanovich
Robert Demyanovich 2021-6-22
Thanks, but couldn't I write what you have written as follows. Or is there a difference?
if (dS(i+1,:)> cA(i+1,:)) | (dS(i+1,:)> cB(i+1,:));
dS(i+1,:) = min(cA(i+1,:),cB(i+1,:));
end
Mohammad Sami
Mohammad Sami 2021-6-22
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
false

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Chemistry 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by