How can I effectively extract and replace a rectangular subpart of a toroidal matrix, i.e. one where boundaries are connected at opposite ends? Since the submatrix can overhang the edges, a simple Take
won't work, as the submatrix cannot be extracted if it is not continuous. At present, I construct a table of positions that are extracted/replaced via ReplacePart
, but I feel there must be more elegant and faster solutions. Such answers could add to the usefulness of Elegant operations on matrix rows and columns. Consider the following example:
n = 8; (* matrix edge length *)
m = 4; (* submatrix edge length *)
matrix = Table[0, {n}, {n}];
sub = RandomReal[{.2, 1}, {m, m}]; (* random submatrix *)
pos = {6, 7}; (* position of sub assuming bottom left corner as origo *)
subPos = Table[{i, j}, {i, m}, {j, m}];
repPos = Map[Mod[# + pos - 1, n, 1] &, subPos, {2}]; (* list of positions to extract *)
new = ReplacePart[ReplacePart[matrix, Flatten@MapThread[Rule, {repPos, sub}, 2]], pos -> 2];
(* Replace the explicit list of positions with the elements of sub *)
ArrayPlot[Reverse@Transpose@new,
ColorRules -> {2 -> Pink, 0 -> White}, Mesh -> All, ImageSize -> 300]
Pink cell indicates the origin of the submatrix.
Question: Can the extraction/replacement done faster, assuming that matrix
and sub
could be huge (e.g. 10 000x10 000 and 50x50, respectively)?