speed up "subs" function or faster alternative ways for symbolic substitution

50 visualizaciones (últimos 30 días)
I am simulating a robotic system with symbolic dynamic matrices of the robot. When I used "subs" function to substitute the symbolic variables, it took around 0.03 seconds for 1 matrix. This is relatively slow because I will need to do this a thousand times for 1 second of simulation. I also tried using matlabFunction, but it took longer to finish, around 0.5s!
So my question is is there any way to speed up the symbolic substitution?
  9 comentarios
Walter Roberson
Walter Roberson el 3 de Ag. de 2023
Sometimes when you have an expression that repeats a number of sub-expressions, then the symbolic engine might store references to the sub-expressions, and during calculation might only evaluate the common sub-expression once. However when you convert to function handle, the sub-expressions need to be evaluated each time.
For example, suppose you had the symbolic expression
(sin(gamma(x))-1)^3 + 5*(sin(gamma(x))-1)
then the symbolic engine might internally represent that as
temporary_node1 = sin(gamma(x))-1
result = temporary_node1^3 + 5*temporary_node1
but the anonymous function handle
@(x) (sin(gamma(x))-1)^3 + 5*(sin(gamma(x))-1)
would require execution of the sin(gamma(x))-1 each time.
If that is what is happening, then you can often get better numeric performance by using
h = matlabFunction(EXPRESSION, 'file', 'FileNameGoesHere.m', 'optimize', true)
which would do an analysis to find common sub-expressions and would write file FileNameGoesHere.m containing optimized code.
There are at least two problems with using this approach:
  1. the optimization itself to find common sub-expressions can take a long time. For longer expressions, it can take literally hours. You need to ask the question of whether faster resulting .m file is going to be executed enough times that the total time saved will make up for the minutes to hours spent trying to find the optimal version of the code;
  2. historically, the optimization routine has had serious bugs. I do not know if all of those bugs have been fixed.
Tuan Hua
Tuan Hua el 3 de Ag. de 2023
Thanks for your help, Walter! I think it is better to use the subs function with symbolic variable in my case!

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Formula Manipulation and Simplification en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by