Reduce length of sum of products of symbolic variables
3 views (last 30 days)
I am using Matlab symbolics toolbox to simplify an expression which is a sum of many single-variable products, where variables re-occur:
G1*P3 + G1*P5 + G1*P6 + G2*P3 + G2*P6 + G3*P2 + G3*P5 + G4*P2 + G4*P3 + G4*P5 + G4*P6 + G5*P2 + G5*P3 + G5*P5 + G5*P6 + G6*P3 + G6*P6 + G7*P2 + G7*P5 + G8*P2 + G8*P3 + G8*P5 + G8*P6
(created by using a loop with sym(sprintf('G%d', i))
Using simplify does not change the expression. I tried a custom command using collect(tmp,sym(sprintf('P%d', i))) in a loop. However, this simplifies up to
(G3 + G4 + G5 + G7 + G8)*P2 + (G1 + G2 + G4 + G5 + G6 + G8)*P3 + (G1 + G2 + G4 + G5 + G6 + G8)*P6 + (G1 + G3 + G4 + G5 + G7 + G8)*P5
How do I get
(G1 + G2 + G4 + G5 + G6 + G8)*(P3+P6) + (G1 + G3 + G4 + G5 + G7 + G8)*P5 + (G3 + G4 + G5 + G7 + G8)*P2
which is shorter and which you can get from directly looking at the expression? I started creating my own logic for simplification, but that seems not feasible.
I already tried this in Maple (with help by the Maple forum), but I have the expression in Matlab (and hundreds others, which are similiar). I want to omit calling Maple from Matlab for this.
A similar solution in Matlab does not work for me (tmp is expression):
matlabFunction(tmp, 'File', filename_test, 'Optimize', true)
The generated code file is unchanged relative to the initial expression.
Paul on 21 Nov 2022
Edited: Paul on 21 Nov 2022
Would you mind explaining why it's necessary to get the expression into a particular form?
Recreating the expression
E = G1*P3 + G1*P5 + G1*P6 + G2*P3 + G2*P6 + G3*P2 + G3*P5 + G4*P2 + G4*P3 + G4*P5 + G4*P6 + G5*P2 + G5*P3 + G5*P5 + G5*P6 + G6*P3 + G6*P6 + G7*P2 + G7*P5 + G8*P2 + G8*P3 + G8*P5 + G8*P6
Surprised that simplify can't do better.
One option might be to use coeffs.
[co,terms] = coeffs(E,P)
Use unique to find unique coeffiecients.
[uniqueco,iuniqueco,ico] = unique(co)
Loop through the unique coefficients and combine with sum of corresponding terms:
Enew = 0;
for ii = 1:numel(unique(co))
Enew = Enew + uniqueco(ii)*sum(terms(ico == ico(ii)));