Info

# Can this line in a code be written in a smarter way?

3 views (last 30 days)
Christina Sørensen on 23 Oct 2019
Closed: MATLAB Answer Bot on 20 Aug 2021
This is the line in the code:
C(:,:,c)=(dC*C(:,:,c)+(dC*C(:,:,c)')'+C(:,:,c)*(-b)+C(:,:,c));
I am trying to make the code work faster since it takes a very long time to run, and this is the only part of the code I can not figure out if it can be rewritten.
The code is describing how the chemicals in the simulation difusses.
Christina Sørensen on 23 Oct 2019
Yes I know this is not good code it some I have gotten from a collegue, and need to try and do some further work with.
dC is a 80x80 matrix
b is the number 80
C is a matrix with the dimensions 80x80x10
c is an array going from 1 to 10
hope this helps

Steven Lord on 23 Oct 2019
I agree with John's assessment. Unless dC, b, and C are terms of art for chemical diffusion problems I'd use more descriptive variable names. If you show this code to someone else, or if you need to revisit it six months from now, will it be easy to understand what it's doing?
But reordering the terms can help slightly:
C(:,:,c)=(dC*C(:,:,c)+(dC*C(:,:,c)')'+C(:,:,c)*(-b)+C(:,:,c));
Remove an extraneous pair of parentheses.
C(:,:,c)=dC*C(:,:,c)+(dC*C(:,:,c)')'+C(:,:,c)*(-b)+C(:,:,c);
Reorder terms.
C(:,:,c)=dC*C(:,:,c)+C(:,:,c)*(-b)+C(:,:,c)+(dC*C(:,:,c)')';
Assuming b is a scalar, combine the first two terms. If it's not there's still a way to simplify this, using the result of a later step.
C(:,:,c)=(dC-b)*C(:,:,c)+C(:,:,c)+(dC*C(:,:,c)')';
Combine the new first two terms.
C(:,:,c)=(dC-b+1)*C(:,:,c) + (dC*C(:,:,c)')';
Use the fact that (A*B)' = B'*A'.
C(:,:,c)=(dC-b+1)*C(:,:,c) + C(:,:,c)*dC';
If b is not a scalar, -b would be combined with the second term here not the first. This is the later step I referenced above.
Assuming dC and b don't change inside the loop over the pages of C you can precompute (dC-b+1) and dC' before the loop. This avoids needing to transpose slices of C then transpose a second time.
And one nitpick: unless C is of size 1 in the third dimension, it's not a matrix as ismatrix will return false.

Jos (10584) on 23 Oct 2019
as others have mentioned before this makes ones head spin ... However,
C(:,:,c)=(dC*C(:,:,c)+(dC*C(:,:,c)')'+C(:,:,c)*(-b)+C(:,:,c)) ;
is equal to
M = C(:,:,c) ; % slice of C
C(:,:,c) = dC*M + (dC*M')' + M*(-b) + M ;
which, imho, is way easier to read. An now it is easy to see the one Steven ended up with:
M = C(:,:,c) ;
C(:,:,c) = (dC-b+1)*M + M*dC' ;