Assume that I have a 2D array A
and I want to do something like this
N1, N2 = 4, 3
A = ones((N1, N2))
x = zeros(N1)
for i2=1:N2
for i1=1:N1
x[i1] = 2 * A[i1, i2]
end
end
x = zeros(N2)
for i1=1:N1
for i2=1:N2
x[i2] = 2 * A[i1, i2]
end
end
Then, in case of 3D array A
I will need to add one extra loop:
N1, N2, N3 = 4, 3, 2
A = ones((N1, N2, N3))
x = zeros(N1)
for i3=1:N3
for i2=1:N2
for i1=1:N1
x[i1] = 2 * A[i1, i2, i3]
end
end
end
# etc.
Now let’s assume I have an n-dimensional array A
, and I want to specify some axis ax
along which I want to multiply A
by 2 and put the result to x
(similarly to the above examples). The corresponding pseudo code can look like
ax = m
A = zeros((N1, N2, ..., Nn))
x = zeros(Nm)
for in=1:Nn
for i(n-1)=1:N(n-1)
...
for i(m+1)=1:N(m+1)
for i(m-1)=1:N(m-1)
...
for i2=1:N2
for i1=1:N1
for im=1:Nm
x[im] = 2 * A[i1, i2, ..., i(m-1), im, i(m+1), ..., i(n-1), in]
end
end
end
...
end
end
...
end
end
However, I want a generic code which will not depend on the number of A
dimensions, i.e. some function foo(x, A, ax)
which will do what I want independently of the size of A
. How I should write such kind of code with loops for arbitrary dimension of A
?
So far I found only this old blog post which proposes to use macros. Did something changed since then? Can the corresponding loops be written with ndims
and axes
functions without macro?