How to make a long equation line more efficient?

5 views (last 30 days)
I am running an optimization that is taking too long.
As I profiled my code, I figured out that what is taking most of the time is one line of code that is evaluating a variable. Everything is in vector form (relatively big one) and that line of code is also pretty long (pages).
First thing that crossed my mind was to symbolically simplify the equation, to make it shorter and to [hopefully] reduce the number of operations.
The second thing I did was to see if I have any term with those vectors being to power of something. I precalculated them and used the precalculated values in this line of code instead (for example E2 = E.^2, E3 = E2.*E and so on). I thought this should help because I have hundreds of these instances - even though I am creating and storing new variables (turned out to be not a big help though).
I was wondering if anyone thinks of any other method to make my code faster. I have done columns vs rows already for storing the vectors.
I was also wondering if I can have Matlab find terms that have repeated often without I inspect pages of code myself. For example, if (v+1)^2 is repeated, so I can precalculate it and save some time.
Any help will be appreciated.

Answers (1)

Matt J
Matt J on 30 Jul 2019
Edited: Matt J on 30 Jul 2019
I thought this should help because I have hundreds of these instances
If the expression came from matlabFunction, be sure you are outputting to a file, not to an anonymous function, and make sure that the Optimize flag is active (it should be, by default). You should not have repeated instances of anything if everything is set up this way.
  2 Comments
Siavash
Siavash on 30 Jul 2019
What I do is to use simplify() function and then use diary to print it to a file since command window does not show the whole equation.
For the optimization part, I am using the actual equation (copied) to evaluate the variable.
What I meant by repetition of terms was in different terms of the equation.
For example, like repetition of V^2 (V being a vector) here:
a/b*c*V^2/(....) + (b^4*V^2)^(7/3) +((V^2)*5*d*e)^(V^2) ....
Walter Roberson
Walter Roberson on 30 Jul 2019
matlabFunction() to a file with 'Optimize' on will (probably) optimize those repeated V^2
Unfortunately optimization can take a long time.
Note: in order to write out the entire symbolic expression, I wrote the following helper function:
function symwrite(expression, filename)
feval(symengine, '_assign', 'TemporaryName', expression);
cmd = sprintf('fid := fopen("%s", Write, Text); fprint(fid, TemporaryName); fclose(fid);', filename);
evalin(symengine, cmd);
This writes the expression to the given file. However, what it writes will be in MuPAD format, not in Symbolic Expression format. MuPAD format has its uses.

Sign in to comment.

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!