# Enumerating over matrix element values in Table

I have a $$N$$ dimensional array $$M$$, and a function $$f(\{M_{i}\})$$ in terms of the array elements, where each matrix element $$M_{i}$$ can be 0 or 1. I'd like to construct a table

Table[f(\{M_{ij}\}), {M_{1},0,1},{M_{2},0,1},...,{M_{N},0,1}]


For a given N, I can write down the code to construct the table, but for general N, it there a convenient way to write the above code? Namely, I'd like to keep N as an input variable.

As an example, let us use

n=3;
Mat=Table[M[i],{i,1,n}];


and define f as the sum of all the elements in Mat. so the table I want to construct is

Table[Sum[M[i],{i,1,n}], {M[1],0,1},{M[2],0,1}, {M[3],0,1}]


The outcome is

{{{0, 1}, {1, 2}}, {{1, 2}, {2, 3}}}


Of course, when I change n to other values, I need to rewrite the code for the table. So there should be a way for us to construct the table without modifying the code.

• It seems to me that you want to Map your function $f$ on each element of the matrix $M$. Would Map[f, M, {2}] do what you want? Commented May 23, 2020 at 18:03
• $f$ depends on every element of $M$, not just one particular element. So I think we need some more complicated form. Commented May 23, 2020 at 18:15
• Can you give an example input with the desired example output? That would help. Commented May 23, 2020 at 18:20
• @user34104 Yes, so you will have defined f[mi_] := <do something with the mi value> so for each different value in $M$, $f$ will do whatever you want with it. I second @march’s request though. If you show us an example of input and desired output, this will be much easier. Commented May 23, 2020 at 18:33
• Thanks! I've updated with an example. Commented May 23, 2020 at 18:37

From one example it is not clear what you want for other than n = 3, perhaps

Clear["Global*"]

Mat[n_] :=
Table[Sum[M[i], {i, 1, n}],
Evaluate[Sequence @@ ({M[#], 0, 1} & /@ Range[n])]]

Mat[3]

(* {{{0, 1}, {1, 2}}, {{1, 2}, {2, 3}}} *)

Mat[5]

(* {{{{{0, 1}, {1, 2}}, {{1, 2}, {2, 3}}}, {{{1, 2}, {2, 3}}, {{2,
3}, {3, 4}}}}, {{{{1, 2}, {2, 3}}, {{2, 3}, {3, 4}}}, {{{2,
3}, {3, 4}}, {{3, 4}, {4, 5}}}}} *)


ClearAll[Mat]
Mat[n_Integer] := Nest[Partition[#, 2, 1] &, Range[0, n], n - 1]

Mat[3]

(* Out: {{{0, 1}, {1, 2}}, {{1, 2}, {2, 3}}} *)


% == {{{0, 1}, {1, 2}}, {{1, 2}, {2, 3}}} (* Out: True *)

Mat[5]
`