计算矩阵中的交叉对角元素的总和 [英] Calculate the sum of cross-diagonal elements in a matrix
问题描述
- -----------------
| 1 | 2 | 3 |
-------------------
A = | 4 | 5 | 6 |
-------------------
| 7 | 8 | 9 |
-------------------
<
pre code $ ____ ____ ____ ____
B = | 1 | 6 | 15 | 14 | 9 |
| ____ | ____ | ____ | ____ | ____ |
第一个交叉对角线 A [0] [0]
将被复制到 B [0]
。
A [1] [0]
和 A [0] [1]
将被添加并复制到 B [1]
, ie 4和2将被添加。然后下一个交叉对角元素 code> A [2] [0] 和 A [1] [1]
和 A [0 ] [2]
将被添加并复制到 B [2]
,即 7,5和3将会添加。等等...
对于每个对角线,行索引和列索引的总和等于B数组的索引。基于这个事实,你可以像这样做一个算法:
$ pre code> //假设矩阵的宽度和长度是N
//很好,你对这个想法的范围有一些想法,试试看你自己?
//对于(int i = 0; i
的函数; j ++){//考虑为什么j应该在范围内(0,i)?
//一些累计在这里添加
}
}
I want to add together the cross-diagonal elements in a matrix. For example, I have a 3*3 Matrix which is two dimensional, I want to convert it to one dimensional:
-------------------
| 1 | 2 | 3 |
-------------------
A= | 4 | 5 | 6 |
-------------------
| 7 | 8 | 9 |
-------------------
final output will be,
____ ____ ____ ____ ____
B= |1 | 6 | 15 | 14 | 9 |
|____|____|____|____|____|
First cross-diagonal A[0][0]
will be copied to B[0]
.
Then the next cross-diagonal elements A[1][0]
and A[0][1]
will be added and copied to B[1]
, i.e. 4 and 2 will be added.
Then the next cross-diagonal elements A[2][0]
and A[1][1]
and A[0][2]
will be added and copied to B[2]
, i.e. 7, 5 and 3 will be added.
And so on...
Notice that for each diagonal, the sum of row-index and column-index is equal to the index of B array. Based on this fact, you can make a algorithm like this:
// assuming the width and length of the Matrix is N
// it's good you have some ideas of the range of idea, try figure it out by yourself?
// definitely it should be a function of N
for (int i=0;i<F(N);i++) {
for (int j=0;j<=i;j++) { // consider why j should be in range (0,i) ?
// some cumulatively add here
}
}
这篇关于计算矩阵中的交叉对角元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!