# Symbolic replacement of scalar products

1. Jul 4, 2011

### Jusepè

Hello,

I have very complicated expressions containing scalar products like

a1*b1 + a2*b2 + a3*b3

In order to reduce the complexity, I would like to establish a set of rules like

rule={a1*b1 + a2*b2 + a3*b3 -> pAB, ...}

in order to replace each time the scalar product by an appropriate new symbol (pAB in the example).
The problem is that, apparently, Mathematica does not perform the substitution if in the expression the scalar products appear together with some multiplying factor; for example Mathematica fails to apply the previous rule if the expression is

-a1*b1 - a2*b2 - a3*b3

or

2a1*b1 + 2a2*b2 + 2a3*b3

How could solve this problem?

2. Jul 4, 2011

### Bill Simpson

Some things within Mathematica "understand mathematics", they have a lot of programming hiding in the background that simulates common sense math.

Replacement rules specifically document that they do not do this. They work on the raw underlying, often hidden, form of the expressions.

Usually a helpful technique for getting more complicate patterns to work when you don't have a lot of experience to be able to guess what to do is to look at

FullForm[-a1*b1 - a2*b2 - a3*b3]

and see what it is that Mathematica is going to match. Then you can sometimes write a pattern that will match that FullForm.

So for example in your case, perhaps one or perhaps two patterns might be needed, one that includes a positive scale factor in front of all the terms and possibly a second that includes a negative scale factor, if the FullForm shows you that your expression with minus signs is really different from the one with a plus sign. Look at FullForm[x*y] and then FullForm[x/y] if you want to see a hint of how different the internal form can be.

So, just to give you an idea, you might want a rule something in the direction of

x_*a1*b1 + x_*a2*b2 + x_*a3*b3 -> pAB
or possibly
x_*a1*b1 + x_*a2*b2 + x_*a3*b3 -> x*pAB

That is trying to match all your ai*bi when multiplied by the same scale factor named x.

See if this description makes sense and try it on a few simple examples first.

Over the years pattern matching has been a source of confusion and problems for users. There has been some interest in pattern matching that would understand mathematics or that would overcome some of the problems people have, but it seems that this has never been accepted.