I wrote the following function to make a 2-D array object odd-dimensioned by adding a row or column as needed (where sizeX, sizeY, get, set, and resize are self-explanatory grid2D member functions).
void makeOdd(grid2D<double> *pSrc)
// ---------------------------------------------------------------------------------------------------------
// Make one or both dimensions of input array odd (via row/column copy).
{
// Variable declarations
grid2D<double> pTmp = *pSrc; // Scratch local source variable
int simax, sjmax; // Source dimensions
// Get source dimensions
sjmax = pSrc->sizeY();
simax = pSrc->sizeX();
// Check if source is already odd-dimensioned
if (sjmax%2 && simax%2) return;
// Extend row/column of source if necessary
if (sjmax%2 && !(simax%2)) // Odd rows, even columns
{
pSrc->resize(simax+1,sjmax); // Resize source with extra column
for(int i=0; i<simax+1; i++)
{
for(int j=0; j<sjmax; j++)
{
if(i==simax)
pSrc->set(i,j,pTmp.get(simax-1,j)); // Copy last column
else
pSrc->set(i,j,pTmp.get(i,j));
}
}
return;
}
else if (!(sjmax%2) && simax%2) // Even rows, odd columns
{
pSrc->resize(simax,sjmax+1); // Resize source with extra row
for(int i=0; i<simax; i++)
{
for(int j=0; j<sjmax+1; j++)
{
if(i==simax)
pSrc->set(i,j,pTmp.get(i,sjmax-1)); // Copy last row
else
pSrc->set(i,j,pTmp.get(i,j));
}
}
return;
}
else // Even rows, even columns
{
pSrc->resize(simax+1,sjmax+1); // Resize source with extra row and column
for(int i=0; i<simax+1; i++)
{
for(int j=0; j<sjmax+1; j++)
{
if(i==simax && j==sjmax)
{
pSrc->set(i,j,pTmp.get(simax-1,sjmax-1)); // Copy last column and row
}
else if(i==simax && j<sjmax)
{
pSrc->set(i,j,pTmp.get(simax-1,j)); // Copy last column
}
else if(i<simax && j==sjmax)
{
pSrc->set(i,j,pTmp.get(i,sjmax-1)); // Copy last row
}
else
{
pSrc->set(i,j,pTmp.get(i,j));
}
}
}
return;
}
}
My question: is there a cleaner/more efficient way of doing this?
Many thanks…
I think it would be easier to check the number of rows first, and extend it by 1 if needed. Then, check the number of columns, and extend each of them by 1 if needed.
Assuming your
grid2dis a wrapper around avector<vector<T> >, you can pass a value toresizethat it will use to fill the newly created space, so when you add a row, you can just pass current last row to get it copied into the new last row.