# 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:

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}]? – Unbelievable Jan 21 '16 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 Jan 21 '16 at 18:37
• Damn, both of my favorite methods in one post. Nothing left for me to write. :^) – Mr.Wizard Jan 21 '16 at 18:44
• The second way is so intelligent, I enjoyed it. – Unbelievable Jan 21 '16 at 18:44
• @Ackaran See the question I just linked in a comment below your post for more examples like this. – Mr.Wizard Jan 21 '16 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 Jan 22 '16 at 11:32
• @Kuba, I see it, but the OP asked for MapAt. I've made it just for fun :))) – garej Jan 22 '16 at 11:33
• BTW, this Replace[m1, {a_, b_, c_, d_} -> {c, b, a, d}, {2}] also does the job. – garej Jan 23 '16 at 9:02