ReplacePart

The ReplacePart function is well documented.  Below I give useful function that uses  ReplacePart.

SwapParts[expr_, pos1_, pos2_] := ReplacePart[#, #, {pos1, pos2}, {pos2, pos1}] &[expr]


In the next cell I make a matrix and I swap the parts at positions {1,2} and
{3,2}.

mtrx = {{11, 12, 13, 14}, {21, 22, 23, 24}, {31, 32, 33, 34}, {41, 42, 43, 44}} ;      SwapParts[mtrx, {1, 2}, {3, 2}]

{{11, 32, 13, 14}, {21, 22, 23, 24}, {31, 12, 33, 34}, {41, 42, 43, 44}}

In the next cell I swap the first row with the third row.

SwapParts[mtrx, {1}, {3}]

{{31, 32, 33, 34}, {21, 22, 23, 24}, {11, 12, 13, 14}, {41, 42, 43, 44}}


Next I demonstrate that SwapParts can work with arbitrary expressions as well
as matrices.

Clear[x, y, z] ;  demo = (2x - Sqrt[3 + y^2])/(-4 + z^2)

(2 x - (3 + y^2)^(1/2))/(z^2 - 4)

SwapParts[demo, {1, 2}, {2, 1, 2}]

(2 x + z^2)/(-(3 + y^2)^(1/2) - 4)


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page