MATLAB Answers

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

1 view (last 30 days)
Christina Sørensen
Christina Sørensen on 23 Oct 2019
Answered: Jos (10584) on 23 Oct 2019
This is the line in the code:
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
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

Sign in to comment.

Answers (2)

Steven Lord
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:
Remove an extraneous pair of parentheses.
Reorder terms.
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.
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)
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' ;
Please note that adding spaces greatly enhances reading and comes to no extra costs.


Community Treasure Hunt

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

Start Hunting!

Translated by