# faster way to replace entries in a large labelled matrix

suppose i have a matrix such as matr = RandomInteger[{1,100},{5000,5000}] and a list of rules for replacement e.g.

rules = {1 -> 52, 9 -> 53, 15 -> 54, 24 -> 55, 37 -> 56, 44 -> 57, 50 -> 58,
52 -> 59, 3 -> 2, 2 -> 3, 4 -> 4, 5 -> 5, 6 -> 6, 7 -> 7, 8 -> 8,
11 -> 9, 12 -> 10, 10 -> 11, 13 -> 13, 14 -> 14, 16 -> 15, 17 -> 16,
20 -> 17, 19 -> 18, 18 -> 19, 21 -> 20, 22 -> 21, 23 -> 22, 26 -> 23,
25 -> 24, 27 -> 25, 28 -> 26, 29 -> 27, 30 -> 28, 31 -> 29,
32 -> 30, 36 -> 31, 33 -> 32, 35 -> 33, 34 -> 34, 38 -> 36, 41 -> 37,
39 -> 38, 40 -> 39, 43 -> 40, 42 -> 41, 45 -> 42, 46 -> 43,
47 -> 44, 48 -> 47, 51 -> 49, 49 -> 50};


The slowest method i have found is using ReplaceAll without Dispatch

matr/.rules; //AbsoluteTiming (* {42.8779, Null} *)

with Dispatch applied on rules the operation becomes significantly fast:

matr /. Dispatch[rule]; // AbsoluteTiming (* {5.45279, Null} *)

An even faster approach i found is using Replace with Dispatch:

Replace[matr, Dispatch@rule, {2}]; // AbsoluteTiming (* {3.00676, Null} *)

Is there a faster/better approach than the one mentioned above?

• Related: (4571), (41753) Jul 30, 2017 at 15:47
• I think this question has a duplicate but I cannot find one. Does this seem overly familiar to anyone else? Jul 30, 2017 at 15:59

For this particular example, you can get an order of magnitude improvement as follows:

matr = RandomInteger[100, {5000, 5000}];
foo = Range[0, 100];
foo[[1 + rules[[All, 1]]]] = rules[[All, 2]];

r1 = Replace[matr, Dispatch@rules, {2}]; // AbsoluteTiming
r2 = foo[[1 + #]] & /@ matr; // AbsoluteTiming

r1 === r2


{3.50752, Null}

{0.390195, Null}

True

• thanks for the great answer ! +1 Jul 27, 2017 at 17:21
• just a general comment. this method will not work if there are any zeros present in the matrix Jul 27, 2017 at 17:38
• @AliHashmi It is possible to modify my answer to work with 0s, is that a requirement? Does the matrix ever have negative numbers? Jul 27, 2017 at 18:04
• i think it would be wonderful if 0 can be incorporated. The matrix does not have negative numbers Jul 27, 2017 at 23:44