# Replacement in a nested matrix

We have a nested matrix

m1 = {{{1, 2, 2, I}, {1, 1, -2, 1}, {3, 2, 2, -I}}, {{3, 4, 4, I}, {1, 1, 4, 1}, {3, 3, 4, -1}}};


we must replace the first number of each sub_list with the third number and vise versa and and achieve to m2 as:

m2 = {{{2, 2, 1, I}, {-2, 1, 1, 1}, {2, 2, 3, -I}}, {{4, 4, 3, I}, {4, 1, 1, 1}, {4, 3, 3, -1}}};


The shape of m1 and m2 are as below. We know that we can use of two loops with an IF condition but we don't think it is a good way. If Possible please let us know how can we obtain m2?

m1:

m2:

• Closely related: (3069), (47017) Commented Jan 21, 2016 at 18:45

One way:

m2 = Apply[{#3, #2, #, #4} &, m1, {2}]


or another:

m2 = m1;
m2[[;; , ;; , {3, 1}]] = m2[[;; , ;; , {1, 3}]];
m2

• Can I use of MapAt instead of Apply[ ,{2}]? Commented Jan 21, 2016 at 18:36
• @Ackaran Apply is shorter because with Map you have to refer to #[[2]] instead of #2 etc. And you need Map not MapAt.
– Kuba
Commented Jan 21, 2016 at 18:37
• Damn, both of my favorite methods in one post. Nothing left for me to write. :^) Commented Jan 21, 2016 at 18:44
• The second way is so intelligent, I enjoyed it. Commented Jan 21, 2016 at 18:44
• @Ackaran See the question I just linked in a comment below your post for more examples like this. Commented Jan 21, 2016 at 18:45

"Monster voodoo machine" method for those who want MapAt, do not want to bother with Part and like Span:

MapAt[Replace[{a_, b_, c_, d_} -> {c, b, a, d}], m1, {;; , ;;}]

• You can use Map[Replace[...], m1, {2}] too.
– Kuba
Commented Jan 22, 2016 at 11:32
• @Kuba, I see it, but the OP asked for MapAt. I've made it just for fun :))) Commented Jan 22, 2016 at 11:33
• BTW, this Replace[m1, {a_, b_, c_, d_} -> {c, b, a, d}, {2}] also does the job. Commented Jan 23, 2016 at 9:02
 m =
{{{1, 2, 2, I}, {1, 1, -2, 1}, {3, 2, 2, -I}},
{{3, 4, 4, I}, {1, 1, 4, 1}, {3, 3, 4, -1}}};

wanted =
{{{2, 2, 1, I}, {-2, 1, 1, 1}, {2, 2, 3, -I}},
{{4, 4, 3, I}, {4, 1, 1, 1}, {4, 3, 3, -1}}};


Using ReplaceAll:

(m /. v_?VectorQ :> Reverse@RotateRight[v, 1]) === wanted

(*True*)

m =
{{{1, 2, 2, I}, {1, 1, -2, 1}, {3, 2, 2, -I}},
{{3, 4, 4, I}, {1, 1, 4, 1}, {3, 3, 4, -1}}};

wanted =
{{{2, 2, 1, I}, {-2, 1, 1, 1}, {2, 2, 3, -I}},
{{4, 4, 3, I}, {4, 1, 1, 1}, {4, 3, 3, -1}}};


Using SubsetMap (new in 12.0)

result = Map[SubsetMap[RotateRight, #, {1, 3}] &, m, {2}]


returns

 {{{2, 2, 1, I}, {-2, 1, 1, 1}, {2, 2, 3, -I}},
{{4, 4, 3, I}, {4, 1, 1, 1}, {4, 3, 3, -1}}};

result == wanted


True