1
$\begingroup$

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.

$\endgroup$
6
  • 1
    $\begingroup$ 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? $\endgroup$ – MarcoB May 23 '20 at 18:03
  • $\begingroup$ $f$ depends on every element of $M$, not just one particular element. So I think we need some more complicated form. $\endgroup$ – user34104 May 23 '20 at 18:15
  • $\begingroup$ Can you give an example input with the desired example output? That would help. $\endgroup$ – march May 23 '20 at 18:20
  • $\begingroup$ @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. $\endgroup$ – MarcoB May 23 '20 at 18:33
  • $\begingroup$ Thanks! I've updated with an example. $\endgroup$ – user34104 May 23 '20 at 18:37
2
$\begingroup$

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}}}}} *)
$\endgroup$
3
$\begingroup$

Working from your example:

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}}} *)

Checking with your desired output:

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

Also:

Mat[5]

(* Out: 
{{{{{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}}}}}
*)
$\endgroup$

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.