Info
此问题已关闭。 请重新打开它进行编辑或回答。
Can this line in a code be written in a smarter way?
1 次查看(过去 30 天)
显示 更早的评论
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.
4 个评论
John D'Errico
2019-10-23
It hurts my head just to try to read it. Obscenely written code, using c, C, and dC. Good code is easy to read. That makes it easy to debug.
But if you want help, then you can help people to help you by telling us what size and shape these arrays are. I assume that c is a scalar, probably a loop index.
回答(2 个)
Steven Lord
2019-10-23
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.
0 个评论
Jos (10584)
2019-10-23
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.
0 个评论
此问题已关闭。
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!