2 views (last 30 days)

Show older comments

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?

Sulaymon Eshkabilov
on 19 Jun 2021

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
on 19 Jun 2021

Edited: Sulaymon Eshkabilov
on 19 Jun 2021

...

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

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

Start Hunting!