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!