Group Abstract Group Abstract

Message Boards Message Boards

0
|
5.5K Views
|
1 Reply
|
1 Total Like
View groups...
Share
Share this post:

Swap parts of a 2D Table?

Posted 6 years ago

lets say I have the following table.

gs = 7; ts = Table[{i, j}, {j, 1, gs}, {i, 1, gs}];ts//Grid

and I wish to swap parts of columns with another part of a column and the same with rows, then the following works if the spanning part is the same, i.e

m2 = ts; m2[[2 ;; 4, {2, 5}]] = m2[[2 ;; 4, {5, 2}]]; m2 // Grid

and

m2 = ts; m2[[{2, 5}, 2 ;; 4]] = m2[[{5, 2}, 2 ;; 4]]; m2 // Grid

However, changing the spanning part so they are different, causes undesired results, mainly duplicate entries start to appear. So my question is can anyone see a better solution so I can exchange different sections that aren't necessarily in the same row or column. For example I would like to be able to produce this.

ngc = {{{1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {6, 1}, {7, 1}}, {{1, 
     2}, {6, 4}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}}, {{1, 3}, {6,
      5}, {3, 3}, {4, 3}, {5, 3}, {6, 3}, {7, 3}}, {{1, 4}, {6, 
     6}, {3, 4}, {4, 4}, {5, 4}, {2, 2}, {7, 4}}, {{1, 5}, {2, 5}, {3,
      5}, {4, 5}, {5, 5}, {2, 3}, {7, 5}}, {{1, 6}, {2, 6}, {3, 
     6}, {4, 6}, {5, 6}, {2, 4}, {7, 6}}, {{1, 7}, {2, 7}, {3, 7}, {4,
      7}, {5, 7}, {6, 7}, {7, 7}}} // Grid

or

ngr = {{{1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {6, 1}, {7, 1}}, {{1, 
     2}, {5, 6}, {6, 6}, {7, 6}, {5, 2}, {6, 2}, {7, 2}}, {{1, 3}, {2,
      3}, {3, 3}, {4, 3}, {5, 3}, {6, 3}, {7, 3}}, {{1, 4}, {2, 
     4}, {3, 4}, {4, 4}, {5, 4}, {6, 4}, {7, 4}}, {{1, 5}, {2, 5}, {3,
      5}, {4, 5}, {5, 5}, {6, 5}, {7, 5}}, {{1, 6}, {2, 6}, {3, 
     6}, {4, 6}, {2, 2}, {3, 2}, {4, 2}}, {{1, 7}, {2, 7}, {3, 7}, {4,
      7}, {5, 7}, {6, 7}, {7, 7}}} // Grid

Regards.

POSTED BY: Paul Cleary

You can change each position independently by a rule, where you simply give the row and column coordinates of each input and output term. Of course it's not that short, but it does the job.

You can start by creating a rule function ( f [ {term1}, {term2} ] ) that will work with the position coordinates of the terms:

f[{a_, b_}, {c_, d_}] := {ts[[a]][[b]] -> ts[[c]][[d]], 
   ts[[c]][[d]] -> ts[[a]][[b]]};

Then simply put the position coordinates (row followed by the column) of the terms in the code below to make the swap:

ngcx = ts /. 
   Flatten@{f[{2, 2}, {4, 6}], f[{3, 2}, {5, 6}], f[{4, 2}, {6, 6}]} //
   Grid

im1

ngrx = ts /. 
   Flatten@{f[{2, 2}, {6, 5}], f[{2, 3}, {6, 6}], f[{2, 4}, {6, 7}]} //
   Grid

im2

im3

POSTED BY: Claudio Chaib
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard