转置1维数组

所以我有一个N维数值的一维数组,其中N是一个完美的正方形。 我将这个一维数组可视化为二维数组(尽管它不是)。 例如,值为int Array = { 0,1,2,3,4,5,6,7,8 }

那是

 int *Array = new int [9]; for ( int i = 0 ; i < 9 ; i ++ ) Array[i] = i; // For example 

打印为

 0 1 2 3 4 5 6 7 8 

所以,我想在一维数组中交换位置,以便我得到它的转置,…

例如…

 0 3 6 1 4 7 2 5 8 

这基本上是相同的一维数组,但交换值使得数组现在为int Array = {0,3,6,1,4,7,2,5,8}

如果我要将它缩放到1024 * 1024维度的数组,逻辑将如何?

使用n = sqrt(N) ,您可以尝试一些简单的方法:

 for(int i = 0; i < n; ++i) for(int j = i+1; j < n; ++j) std::swap(Array[n*i + j], Array[n*j + i]); 

转置操作对除了矩阵的对角线之外的上三角或下三角执行swap(v[y][x],v[x][y]) (让我们说上面)。

在C一维向量vcv[y][x]对应于vc[y*n+x] 。 所以你想做vc[y*n+x] = vc[x*n+y]

您要交换的元素是x > y的元素。

你最终做了:

 for(int y = 0; y < n; ++y) for(int x = y+1; x < n; ++x) swap(vc[x*n + y], vc[y*n + x]); 

你可以自己想出来......

 #include  #include  using namespace std; int xyToIndex(const int x, const int y, const int size){ return x + y * size; } int main(){ int a[] = { 0,1,2,3,4,5,6,7,8 }; const int size = sqrt(sizeof(a)/sizeof(int)); //print only for(int x = 0;x < size; ++x){ for(int y = 0; y < size; ++y) cout << a[xyToIndex(x,y,size)] << " ";; cout << endl; } //make array int b[size*size]; int index = 0; for(int x = 0;x < size; ++x) for(int y = 0; y < size; ++y) b[index++] = a[xyToIndex(x,y,size)]; for(int i = 0; i< size * size ; ++i){ cout << b[i] << " "; } } 

您可以交换矩阵中的值,也可以在后面的函数中交换解释。

例如,您可以打印(j,I)而不是打印(i,j)并打印转换姿势。

话虽这么说,你想要做什么的exaclty? 如果你看看LAPACK和BLAS,他们的例程会采用控制算法的标志来正常解释它们或者转换它们。

不使用交换function。 len是数组的长度。

 int i,j; N = sqrt(len); int temp[len]; for(i=0;i 
 static unsigned other(unsigned dim0, unsigned dim1, unsigned index) { #if 0 unsigned x0,x1; x0 = index % dim0 ; x1 = index / dim0 ; return x0 * dim1 + x1; #else unsigned mod,val; mod = dim0 * dim1 -1; val = (index==mod) ? mod: (dim1*index) % mod; return val; #endif } 

上面的函数返回索引的“其他”索引(转置矩阵中的索引:=交换x和y)。 dim0和dim1是矩阵的“水平”和“垂直”大小。 #ifdeffed-out部分是天真的实现。 在您的情况下,您可以使用以下内容初始化(或分析)1维数组:

 for (i=0; i < 9; i++) arr[i] = other(3, 3, i);