change operators position increase computational cost

2 views (last 30 days)
Dear all,
I noticed a strange (to me) behavior in my code. I'm solving a system of ODEs using ODE15s. The following term 'prefac' is calculated many times, and I noticed that, if I used the first equation, the calculation is about half of the time faster than using the second equation (~450s VS. ~870s). The only difference is that the term ./T_c is moved from the end of the equation to the beginning. If, during the simulation, I display the difference between the two, the maximum I get is 8e-22. I used 'prefac' to calculate terms in the order of magnitude of 1e-3, and in fact the solution does not change, only the computational cost increase.
prefac = (Mmix_c./param.R) .* (param.eps_c(end,:,:)./param.tau_c(end,:,:)) .* (1-s_c) .* (5.21e-1) .* ((T_c./139.681).^1.823) ./ (T_c);
or
prefac = (1 ./ (T_c)) .* (Mmix_c./param.R) .* (param.eps_c(end,:,:)./param.tau_c(end,:,:)) .* (1-s_c) .* (5.21e-1) .* ((T_c./139.681).^1.823);
do you have some explanation for it?
regards
Mauri

Accepted Answer

Walter Roberson
Walter Roberson on 25 Jun 2011
You would probably get even better performance with
5.21e-1 .* Mmix_c ./ param.R ./ T_c .* ((T_c./139.681).^1.823) .* (1-s_c) .* (param.eps_c(end,:,:) ./ param.tau_c(end,:,:)) ;
That is, do your commutative operation on scalar constants first in the expression, and then do your operations on matrices. There is no point in dividing each element of the matrix result by T_c if the matrix is also being multiplied by a scalar: instead "fold" the division into the scalar so just one division is done and the new scalar is being used for the necessary multiplication.

More Answers (0)

Categories

Find more on Modeling 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!