SeedRandom[1]
dim = 3; mats = 4; n = 3;
databdata = RandomVariate[dist[2, 1], {n, mats, dim, dim}];
databt = RandomVariate[dist[2, 1], {n, mats, dim}];
datab == data
True
TeXForm[datab]TeXForm[data]
nearestvalueF = Map[Nearest, databdata, {3}];
nearestvalues = MapThread[#[#2][[1]] &, {nearestvalueF, databt}, 3];
TeXForm[nearestvalues]
rankofnearestF = Map[Nearest[Sort[#] -> Automatic] &, databdata, {3}];
ranksofnearest = MapThread[#[#2][[1]] &, {rankofnearestF, databt}, 3];
TeXForm[ranksofnearest]
Legended[MatrixForm[Map[Style[#[[1]], (#[[2]] /. {1 -> Red, 2 -> Green, 3 -> Blue})] &,
combined, {-2}], TableDirections -> Row]]],
Placed[Column[Style @@@ Transpose[{{"rank", "first", "second", "third"},
{{Black, 16}, Red, Green, Blue}}], Dividers -> {False, 2 -> True}], Right]]
nearestValuesAndRanksF = Map[Nearest[Sort[#] -> {"Element","Index"}] &, databdata, {3}];
combined2 = MapThread[#[#2][[1]] &, {nearestValuesAndRanksF, databt}, 3];
combined2 == combined