c - 交换矩阵中的反对称元素

标签 c matrix

我试图改变数组的一个元素,从它的位置 a(不确定它是否这么说)到它相对于矩阵中心的反对称位置,如果要交换的位置构成中心的一部分,则什么都不应该完成(取决于矩阵,中心可以是 1,2 或 4 个单元格):

1  2  3  4  5 
6  7  8  9  10 
11 12 13 14 15 
16 17 18 19 20 
21 22 23 24 25 

中心将是:13

一个例子是将数字 2 换成数字 24。我曾想通过计算我必须在 x 和 y 中从中心到元素位置 (dx dy) 的位移来做到这一点,则从中心到达反对称位置的位移为 -dx -dy。

int mat [][5]={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}};
int aux;
int i = 0;
int j = 1;          // i and j are the indeces of the element to be exchanged
int xcenter=col/2;
int ycenter=fil/2;  // xcenter and xcenter are the indeces of the center
int dx = j-xcenter;
int dy = i-ycenter; // dx dy are the displacements
aux=mat[i][j];
mat[i][j]=mat[xcenter-dx][ycenter-dy];
mat[xcenter+dx][ycenter+dy]=aux;

当矩阵具有奇数列或奇数行时,我的问题就来了,因为在这种情况下,中心将不是一个位置,而是一个集合。比如这个5*4的矩阵

1  2  3   4
5  6  7   8
9  10 11 12
13 14 15 16
17 18 19 20

中心将是:

10 11

不知道找圆心,从圆心的哪个元素算位移。

最佳答案

您可以像这样简化您的坐标计算:

xcenter-dx = xcenter - (j-xcenter) = 2*xcenter - j = 2*col/2 - j = col - j

同样

xcenter+dx = j
ycenter-dy = fil - i
ycenter+dy = i

所以您在将奇数除以二时没有问题。

关于c - 交换矩阵中的反对称元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43419845/

相关文章:

c++ - 错误 : cannot convert 'float (*)[(((sizetype)(((ssizetype)n) + -1)) + 1)]' to 'float (*)[100]' for argument '3'

c - Linux TCP套接字崩溃

c - 写入和打印两个字符串交替组合时出现段错误?

python - mysql c 的 ctypes 错误

r - 两个未知数的线性方程组

c - C中的图像平滑问题

c++ - 矩阵 A 的 boolean 积

c - 在特定顶点上使用 glLoadMatrixd ?

c++ - (unsigned char)str 与 str + 0xff 或 (unsigned int)value 与 value + 0xffff 哪个是更快的首选方法?

代码只有 2 个输入,尽管它有 3 个 fgets