4

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:

enter image description here

m2:

enter image description here

user64494
  • 26,149
  • 4
  • 27
  • 56
Unbelievable
  • 4,847
  • 1
  • 20
  • 46

4 Answers4

6

One way:

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

or another:

m2 = m1;
m2[[;; , ;; , {3, 1}]] = m2[[;; , ;; , {1, 3}]];
m2
Kuba
  • 136,707
  • 13
  • 279
  • 740
3

"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, {;; , ;;}]
garej
  • 4,865
  • 2
  • 19
  • 42
2
 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)

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
1
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

eldo
  • 67,911
  • 5
  • 60
  • 168