MATLAB: Vectorizing four nested for loops

for loopsnested loopsvectorization

If I have a one-dimensional array A of size n and I need to create a new two-dimensional array R from the elements of array A, I can do it using two nested loops:
for i = 1:n
for j = 1:n
R(i,j) = A(i) + A(j);
end
end
Or I can use vectorization:
[i, j]=ndgrid(1:n);
R = A(i)+A(j);
If array A becomes a n by n matrix and I need to create a four dimensional array R I can still use nested loops:
for i = 1:n
for j = 1:n
for k = 1:n
for l = 1:n
r(i,j, k, l) = a(i, j) + a(k, l);
end
end
end
end
Is there a way to replace these four nested loops and use vectorization? Thanks for your help!

Best Answer

Try this:
[i,j] = ndgrid(1:n*n);
r = reshape(a(i)+a(j), [n n n n]);