从(x,y)位置计算对角线元素

时间:2014-04-18 04:44:57

标签: c math

考虑从(0,0)开始的矩阵m*n我想创建一个逻辑来计算应该适用于0<m,n<10^6的对角元素。 例: 考虑, M = 2,n = 3的

A)At 0,0 the only diagonal element will be 1,1

但是

B)
for 0,1 their will be two digonal elements
1)1,0
2)1,2

我无法为矩阵中的任何x,y位置计算对角线元素的通用解决方案。 谁能给我一个指导方向呢?

1 个答案:

答案 0 :(得分:0)

您可以直接计算而不循环,如下所示

//Make the index to normal position
x++;
y++;
//If your x,y is (0,0) it will become (1,1)

//Calculate the rows and columns before and after the current position.
rowsB4 = x - 1 ;
rowsAft = m - x ;
colsB4 = y - 1 ;
colsAft = n - y ;

//Now you can find the lesser number in each of the directions and add it total diagonals

totalDiag = 0 ;

//Left Up
temp = (rowsB4 < colsB4) ? rowsB4 : colsB4 ;
totalDiag += temp ;

//Left down
temp = (rowsAft < colsB4) ? rowsAft : colsB4 ;
totalDiag += temp ;

//Right Up
temp = (rowsB4 < colsAft) ? rowsB4 : colsAft ;
totalDiag += temp ;

//Right down
temp = (rowsAft < colsAft) ? rowsAft : colsAft ;
totalDiag += temp ;