# How to combine two usages of # into one and speed up the code?

I have a function num with two variables, matf and matg. How can I combine the last two lines of code below into one? The code is aimed to find out the maxiaml count bel when we give each $i3 = 1,\cdots,5$ a value $f[[i3]]$ and each $i4 = 1,\cdots,5$ a value $g[[i4]]$. How can I speed up this code? Any help or suggestions will be appreciated.

 FG = Tuples[{0, 1, 2, 3}, 5];
num[matf_, matg_] :=
Module[{f = matf, g = matg},
bel = 0;
For[i3 = 1, i3 <= 5, i3++,
For[i4 = 1, i4 <= 5, i4++,
If[Mod[IntegerPart[(i3 + i4)/2 - 1], 5] == Mod[f[[i3]] + g[[i4]], 5], bel++];
];
];
bel
];
num2[f_] := Max[num[f, #] & /@ FG]
Max[num2[#] & /@ FG]


Here is an example to explain what does num do.

Bell = {};
f = {0, 0, 1, 3, 4};
g = {1, 3, 2, 4, 1};
For[i3 = 1, i3 <= 5, i3++,
For[i4 = 1, i4 <= 5, i4++,
If[Mod[IntegerPart[(i3 + i4)/2 - 1], 5] ==
Mod[f[[i3]] + g[[i4]], 5],
AppendTo[Bell, {f[[i3]], g[[i4]], i3, i4}]];];];
Bell
Bell // Length


The output is

  {{4, 3, 5, 2}, {4, 4, 5, 4}}
2


which means that if we assign each $i3 = 1,\cdots,5$ the i3th element in f={0, 0, 1, 3, 4} and $i4 = 1,\cdots,5$ the i4th element in g={1, 3, 2, 4, 1}, then there is only $i3=5$ (the correspondig value is 4) $i4=2$ (the correspondig value is 2) or $i3=5$ (the correspondig value is 4) $i4=4$ (the correspondig value is 4) satisfy the condition Mod[IntegerPart[(i3 + i4)/2 - 1], 5] == Mod[f[[i3]] + g[[i4]], 5].

• can you define dim? – Pinguin Dirk Oct 6 '13 at 8:31
• could you clarify what the aim of your code is? It appears you wish to count the number of entries of 5-vector matching a constraint by position. There are 1024 tuples, are you wishing to oairwise apply counting function then determine maximum count? – ubpdqn Oct 6 '13 at 9:10
• Your code is very strange. You localize matf and matg, which are already localized, but you fail to localize bel, which would benefit from localization. – m_goldberg Oct 6 '13 at 9:36
• @PinguinDirk Thanks, I update the code. – Eden Harder Oct 6 '13 at 13:02
• @ubpdqn Thanks, yeap. I update the code. – Eden Harder Oct 6 '13 at 13:04

There are two questions embedded in the post, one about combining two lines, and another about efficiency.

### Composition

The last two lines,

num2[f_] := Max[num[f, #] & /@ FG]
Max[num2[#] & /@ FG]


are the same as

Max[Function[f, Max[num[f, #] & /@ FG]] /@ FG]


They are also equivalent to

Max[Max /@ Outer[num, FG, FG, 1]]


or simply

Max[Outer[num, FG, FG, 1]]


### Efficiency

Here's one improvement:

num3[f_, g_] := With[{gt = Transpose[g]},
Length[f]^2 - Total @ Unitize[
Mod[IntegerPart[(#1 + #2)/2 - 1] - (f[[#1]] + gt[[#2]]), 5] & @@
Transpose @ Tuples[Range @ Length @ f, 2]]]

Max[num3[#, FG] & /@ FG] // AbsoluteTiming
(* {0.683202, 21} *)


Almost 200 times faster than the OP's functions.

• Thanks so much! If we also use ft(use like gt) in the code, it will be much faster. – Eden Harder Oct 7 '13 at 8:00