Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factorise symbolic expression (square of a sum) in MATLAB

If I start with the following symbolic expression:

a^2 + 2*a*b + b^2

Then run simplify (or factor), I get the expected result:

>> simplify(a^2 + 2*a*b + b^2)

(a + b)^2

Now when I run the same example, but adding another term, no factorisation occurs:

>> simplify(a^2 + 2*a*b + b^2 + 1)

a^2 + 2*a*b + b^2 + 1

How can I get these functions to return the more practical version of this expression ((a + b)^2 + 1)? I have tried all of the obvious options with these functions (like 'Steps', 'IgnoreAnalyticConstraints', etc.) but to no avail.

Context: I have the expression ax^2 - 2*ax*bx + bx^2 + ay^2 - 2*ay*by + by^2 which I need to convert back into (ax - bx)^2 + (ay - by)^2 so it can then be treated correctly as r^2. I know I could use some blunt substitution rules, but for something so simple I feel like I'm missing an obvious 'non-hack' solution.

like image 414
btalb Avatar asked Feb 10 '16 01:02

btalb


People also ask

How do you factor a symbolic expression in MATLAB?

If x is an integer, factor returns the prime factorization of x . If x is a symbolic expression, factor returns the subexpressions that are factors of x . F = factor( x , vars ) returns an array of factors F , where vars specifies the variables of interest.

How do you represent a summation in MATLAB?

F = symsum( f , k , a , b ) returns the sum of the series f with respect to the summation index k from the lower bound a to the upper bound b . If you do not specify k , symsum uses the variable determined by symvar as the summation index. If f is a constant, then the default variable is x .

How do you force MATLAB to simplify a symbolic expression?

S = simplify( expr ) performs algebraic simplification of expr . If expr is a symbolic vector or matrix, this function simplifies each element of expr . S = simplify( expr , Name,Value ) performs algebraic simplification of expr using additional options specified by one or more Name,Value pair arguments.

How do you define the symbolic mathematics in MATLAB?

Symbolic Math Toolbox™ enables you to perform symbolic computations from the MATLAB® command line by defining a special data type — symbolic objects. Functions are called using the familiar MATLAB syntax and are available for integration, differentiation, simplification, equation solving, and other mathematical tasks.


1 Answers

you can run simplify on the two terms separately.

simplify(ax^2 - 2*ax*bx + bx^2) + simplify(ay^2 - 2*ay*by + by^2)

It seems like you already know how it should be simplified anyway.

Also, you eventually want to write it as r^2. This is not generally possible for all second-order expressions, so don't bother trying to find a general solution.

like image 143
tvo Avatar answered Nov 15 '22 05:11

tvo