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?