# Define a 4d matrix without for loop

I was wondering if there is a way to avoid for loop here:

I want to define a 4d matrix H(i,j,k,l), and each entry in the matrix is calculated through a complex function, say Do_H(i,j,k,l), depending on the index i, j, k, l.

Then I want to squeeze the 4d matrix to a 2d one, in the form below,

H(0,0,0,0)  H (0,0,0,1) ... H(0,0,0,N)... H(0,0,1,0) ... H(0,0,N,N)
H(0,1,0,0)  H (0,1,0,1) ... H(0,1,0,N)... H(0,1,1,0) ... H(0,1,N,N)
...
...
H(N,N,0,0)  H (N,N,0,1) ... H(N,N,0,N)... H(N,N,1,0) ... H(N,N,N,N)


as a (N^2) by (N^2) size matrix. N is predefined.

Thanks!

UPDATE: Sorry if I confused you. There are two questions here:

1. How to calculate each entry without going through the for loop?
2. How to reshape the matrix?

## 2 Answers

Clear[arrayH]
arrayH[n_Integer] := Partition[
Flatten[Array[H, {n + 1, n + 1, n + 1, n + 1}, {0, 0, 0, 0}]],
(n + 1)^2
]

arrayH[3]


Then define an appropriate function H that calculates the value of each item using the indices. By way of example, if you had defined a function:

Clear[H]
H[i_, j_, k_, l_] := StringJoin @@ (ToString /@ {i, j, k, l})


Then

arrayH[3]


Similarly, instead of Flatten and Partition, you can use ArrayReshape to obtain the result in a single operation:

ArrayReshape[
Array[H, {n + 1, n + 1, n + 1, n + 1}, {0, 0, 0, 0}],
{(n + 1)^2, (n + 1)^2}
]

• Wow, this is amazing! Apr 28 '16 at 18:31

Also:

ClearAll[f1, f2, f3, f4]
f1 = Partition[# @@@ Tuples[Range[0, #2], #2 + 1], (#2 + 1)^2] &;
f2 = Partition[Tuples[# @@ Range[0, #2], #2 + 1], (#2 + 1)^2] &;
f3 = ArrayReshape[# @@@ Tuples[Range[0, #2], #2 + 1], {#2 + 1, #2 + 1}^2] &;
f4 = ArrayReshape[Tuples[# @@ Range[0, #2], #2 + 1], {#2 + 1, #2 + 1}^2] &;

f1[H, 3] == f2[H, 3] == f3[H, 3] == f4[H, 3] == arrayH[3]


True