0
$\begingroup$

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.

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

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]]
$\endgroup$
  • $\begingroup$ Yes, this is exactly what I wanted, thank you so much! $\endgroup$ – Alex Jan 13 '17 at 9:35
  • $\begingroup$ 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. $\endgroup$ – Mr.Wizard Jan 30 '17 at 11:42
  • $\begingroup$ @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. $\endgroup$ – Marius Ladegård Meyer Jan 30 '17 at 16:01
2
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.