I have a math function that I would like to use in 1d, 2d, and 3d spaces. I wrote the code to work for the 3-d case and I can easily modify it for the other cases, however I was wondering if there is a way I can write this so that it works with any arbitrary dimensionality. Basically for every dimension there is another nested loop and I don't know how to make multiple nested loops without actually writing them out in the code.
void gen_kernel_Gk(double *Gk, double L, double b, int np, int Z, int m)
{
// Generates Kernel Function G in k-space
// Gk is the array of the function values, it has Z * m number of values
// L is cuttoff distance
// b is monomer size
// np is the degree of polymerization
// Z is the number of modes
// m is the dimensionality of the real space
int i, j, k, l, index, Zhalf;
double pref, kvec[m], k2;
pref = pow( 2 * PI / (double)L, 2) * pow( b, 2) * (double)np / 6.0;
Zhalf = Z / 2;
for( i = 0; i < Z; ++i)
{
if( i < Zhalf)
{
kvec[0] = (double) pow( i, 2);
}
else
{
kvec[0] = (double) pow ( Z - i ,2);
}
for( j = 0; j < Z; ++j)
{
if( i < Zhalf)
{
kvec[1] = (double) pow( j, 2);
}
else
{
kvec[1] = (double) pow ( Z - j ,2);
}
for( k = 0 ; k < Z ; ++k)
{
if( k < Zhalf)
{
kvec[2] = (double) pow( k, 2);
}
else
{
kvec[2] = (double) pow ( Z - k ,2);
}
for( k2 = 0, l = 0; l < m; ++l)
{
k2 += kvec[l];
}
index = i * pow( Z, 2) + j * Z + k;
Gk[index] = 2.0 * ( exp( -k2) + k2 - 1.0) / pow( k2, 2);
}
}
}
return;
}