How does matlab choose the order expressions appear in a symbolic equation? Can I change the order?

20 views (last 30 days)
I have a program that is deriving the equations of motion for an n-tuple pendulum, just as check for myself I displayed the symbolic equations for part of it and noticed the order expressions appear in the equation is different to how I added them in the code.
I go through each value of l(i) and add it to the existing symbolic equation (I'm sure there is a more efficient way of doing this but that's beside the point), however the order in the equations is not only different, but appears to change as the number of l(i) terms changes. How does matlab determine what order the expressions go in the equation and can I tell it to go in a specific order?
% Kinetic energy component of the Lagrangian
syms T_temp T
T = 0;
for i = 1:n
T_temp = 0;
for j = i:n
if j == i
T_temp = T_temp + (1/8)*mass(j);
else
T_temp = T_temp + (1/2)*mass(j);
end
end
T = T + length(i)^2*thetadot(i)^2*T_temp;
end
disp(T);
It has no impact on the final result but when it increases to larger values of n, it would be easy to keep track if they were in order.
Thanks

Accepted Answer

Walter Roberson
Walter Roberson on 31 Jan 2023
the order is not documented, and can involve subtle factors. It can be difficult to figure out the logic.
For example in division by an sum, the terms in the denominator can end up rearranged to avoid starting with a negative coefficient, but sometimes it chooses to instead flip signs in numerator and denominator to get a preferred term to be positive.
There is a sympref() to control whether polynomial powers are increasing or decreasing. That order can end up violated if there is more than one symbolic variable.
collect() can change the order. If you have expressions involving multiple variables, together with a sum of terms that do not involve the variables, then which variable you collect() can alter the order of the terms in the sum that does not involve the variables.
The order of objects you see displayed is not always the same as the internal order of the expression, especially if there is a division. For example a*b/(c*d) might be stored as (a*b) divided by (c*d) but especially if c is a constant the internal representation might be c^(-1)*((a*b)/d)

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!