Include value requirement in array multiplication
1 次查看(过去 30 天)
显示 更早的评论
I currently have the following line of code:
dS=k1*cA(i+1,:).*cB(i+1,:)*dt
dS is the amount of product S resulting from a reaction between A and B, which reaction has a rate constant of k1. cA and cB are the concentrations of A and B respectively and dt is the time step.
Now I would like to specify that a dS value should only be calculated if both the cA cell value and cB cell value which are being multipled are greater than a specific value - in this case 1E-04. If either cA or cB is less than this value, then the result of the multiplication should be zero.
How would I program this requirement in MatLab?
0 个评论
回答(2 个)
Sulaymon Eshkabilov
2021-6-19
for ii=1:N
if cA>1e-4 & cB>1e-4
dS=k1*cA(i+1,:).*cB(i+1,:)*dt;
else
dS = 0;
end
end
Sulaymon Eshkabilov
2021-6-19
编辑:Sulaymon Eshkabilov
2021-6-19
...
N = size(cA, 1);
for ii=1:N
if cA>1e-4 & cB>1e-4
dS(ii,:)=k1*cA(ii,:).*cB(ii,:)*dt;
else
dS(ii,:) = 0;
end
end
%%
Alternative and most efficient way is vectorization and logical indexing:
dS=k1*cA.*cB*dt;
IDX = (cA<1e-4 & cB<1e-4); % Logical indexing
dS(IDX,:)=0; % Takes care of both conditions cA<1e-4 & cB<1e-4
2 个评论
Sulaymon Eshkabilov
2021-6-19
Consider the vectorization approach that is much more efficient and fast.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!