5
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ Related: (4571), (41753) $\endgroup$ – Mr.Wizard Jul 30 '17 at 15:47
  • $\begingroup$ I think this question has a duplicate but I cannot find one. Does this seem overly familiar to anyone else? $\endgroup$ – Mr.Wizard Jul 30 '17 at 15:59
7
$\begingroup$

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.