0

I was looking for a way of, given two variables called A and B, obtaining a new variable called AB. My idea was doing simple pattern matching, e.g.

A B/.x_ y_->ToString[x]<>ToString[y]

But this rule outputs xy instead of the desired AB. Is there a way of obtaining the desired output? Thank you for your time.

Alex
  • 351
  • 1
  • 8
  • Beautiful! Thank you for the effective, quick response. If you post an answer I will give it as the accepted one :) – Alex Jan 13 '17 at 09:33
  • 1
    A B /. x_ y_ :> ToString[x] <> ToString[y] gives "AB" -- see http://mathematica.stackexchange.com/q/22917/121 – Mr.Wizard Jan 30 '17 at 11:41

2 Answers2

2

If you only want to replace the literal variables A and B then you cannot use the pattern x_ y_, as this will match any product of two expressions. Is this what you want?

expr = a^2 + a b + b^2;
expr /. a b -> Symbol[ToString[a]<>ToString[b]]
Marius Ladegård Meyer
  • 6,805
  • 1
  • 17
  • 26
  • Yes, this is exactly what I wanted, thank you so much! – Alex Jan 13 '17 at 09:35
  • This does not make sense to me. If you are not using patterns on the LHS why not just use /. a b -> ab? @Alex same question to you if this really is the solution you want. – Mr.Wizard Jan 30 '17 at 11:42
  • @Mr.Wizard, of course the Symbol[ToString[ is completely superfluous in this case. I just included it to show the OP that it can still be used but with a different LHS, but I see that it may be more confusing than clarifying. – Marius Ladegård Meyer Jan 30 '17 at 16:01
2

Another option

ClearAll[x,A,B,c,d,y,x]
expr = a A B c d y x

Mathematica graphics

expr /. Times[x___, A, B, y___] :> x AB y

Mathematica graphics

Notice that this changes a A B c d y x and A a B c d y x to same result, which is a AB c d x y. But this also happens with the above answer as well, so I assume this is what you wanted.

If on the other hand, you wanted to handle A a B differently from a A B in terms of if A B should be combined or not, then this should be made clear in the question.

Nasser
  • 143,286
  • 11
  • 154
  • 359