       RE: common factors in a matrix

• To: mathgroup at smc.vnet.net
• Subject: [mg33565] RE: [mg33548] common factors in a matrix
• From: "David Park" <djmp at earthlink.net>
• Date: Sun, 31 Mar 2002 04:09:21 -0500 (EST)
• Sender: owner-wri-mathgroup at wolfram.com

```Bart,

Taking common factors out of a matrix and holding them out (Mathematica
automatically multiplies them in) is a common problem. I don't think that
Mathematica has a built in routine to handle this. I wrote the following
routine, which I don't know if I'm ready to vouch 100% for, but it will
handle common cases.

FactorMatrix[(mat_)?MatrixQ] :=
Module[{temp, cfactors, factors,
commonfactor = {}}, temp = Flatten[Factor[mat]];
temp = Map[Replace[#1, 0 -> Sequence[]] & , temp, {1}];
temp = Map[Replace[#1, HoldPattern[Times[a__]] -> {a}, {}] & ,
temp, {1}]; cfactors =
Map[#1 /. {a_^n_ -> {a, n}, a_ -> {a, 1}} & , temp, {2}];
factors = (Intersection[##1, SameTest ->
(#1[] === #2[] & )] & ) @@ cfactors;
Do[Module[{pfactor, exp}, pfactor = First[factors[[i]]];
exp = Last /@ Cases[cfactors, {pfactor, _}, {2}];
exp = If[First[exp] > 0, Min[exp], Max[exp]];
commonfactor = Join[commonfactor, {pfactor^exp}]; ],
{i, 1, Length[factors]}]; commonfactor = Times @@ commonfactor;
HoldForm @@ {commonfactor}*MatrixForm[
Map[Cancel[#1/commonfactor] & , mat, {2}]]]

I can't show the two dimensional form but will show the InputForm. The
common factors are wrapped in a HoldForm so the numerator and denominator
terms will be grouped together. You can get rid of the HoldForm, but then
the matrix will be part of the numerator. Mathematica does not bring factors
outside MatrixForm inside.

mat1 = {{(a + b)^2*c, (a + b)^3*d}, {0, a^2 - b^2}};

FactorMatrix[mat1]
% // InputForm
HoldForm[a + b]*MatrixForm[{{(a + b)*c, (a + b)^2*d}, {0, a - b}}]

On a more general case...

mat2 = {{(a + b)^2*c*(q^2/e/f^(1/2)), (a + b)^3*d*(q^4/e^2/f^(3/2))},
{0, q^3*((a^2 - b^2)/e^4/f^2)}};

FactorMatrix[mat2]
% // InputForm
HoldForm[((a + b)*q^2)/(e*Sqrt[f])]*
MatrixForm[{{(a + b)*c, ((a + b)^2*d*q^2)/(e*f)},
{0, ((a - b)*q)/(e^3*f^(3/2))}}]

David Park

> From: Bart Vorselaars [mailto:fourteen at stack.nl]
To: mathgroup at smc.vnet.net
>
> Hello,
>
> When I have a matrix, say
>
> {{(a+b)c,(a+b)d},{0,a^2-b^2}}
>
> I know how to output it as a matrix in mathematica (MatrixForm). But how
> do I display this matrix as a matrix with the common factor in front of
> it, say:
>
> (a+b)[ c  d   ]
>      [ 0  a-b ]
>
>