我如何从左下角到右上角对角线添加一个矩阵int [,]的值? [英] How could I add the values of a matrix int[,] diagonally from bottomleft, to topright?
问题描述
如何从左下角到右上角将矩阵int [,]的值相加?
How could I add the values of a matrix int[,] diagonally from bottomleft, to topright?
我正试图帮助一位朋友理解这一点,但是即使我真的不明白他们在做什么.
I'm trying to help out a friend understand this but even I don't really get what they're doing here.
这是我想向他解释的方法:
Here's the method I'm trying to explain to him:
public void AddDiagonal()
{
int Addition;
for (int f = 0; f < filas; f++)
{
for (int c = 0; c < columnas; c++)
{
if (f == columnas - c - 1)
{
Addition += matriz[f, c];
}
}
}
}
推荐答案
了解这一点的关键是if
语句:
The key to understanding this is the if
statement:
if (f == columnas - c - 1)
两个嵌套循环遍历行(使用f
作为索引),并为每一行遍历列(使用c
作为索引).
The two nested loops iterate over rows (using f
as an index) and for each row, over columns (using c
as an index).
因此,每次迭代时,您都要测试行号(即f
)是否等于反转的列号(即从列总数中减去c
-
So each iteration, you test if the row number (that is f
) is equal to the column number reversed (that is c
subtracted from the total number of columns - columnas
). The reason you test for the column number reversed is because you want to add from bottom left to top right, which is the same as adding from top-right to bottom left.
要注意的一件事是,对角矩阵仅对方矩阵有意义,这意味着列数必须与行数相同(在您的算法中,filas
应等于columnas
).
One thing to note is that a matrix diagonal only makes sense for a square matrix which means the number of columns needs to be same as the number of rows (in your algorithm filas
should equal columnas
).
因此,假设一个5x5矩阵:
So, assuming a 5x5 matrix:
行0(f = 0)->列4(c = 5-0-1)
第1行(f = 1)->第3列(c = 5-1-1)
第2行(f = 2)->第2列(c = 5-2-1)
第3行(f = 3)->第1列(c = 5-3-1)
第4行(f = 4)->列0(c = 5-4-1)
Row 0 (f = 0) --> Column 4 (c = 5 - 0 - 1)
Row 1 (f = 1) --> Column 3 (c = 5 - 1 - 1)
Row 2 (f = 2) --> Column 2 (c = 5 - 2 - 1)
Row 3 (f = 3) --> Column 1 (c = 5 - 3 - 1)
Row 4 (f = 4) --> Column 0 (c = 5 - 4 - 1)
这篇关于我如何从左下角到右上角对角线添加一个矩阵int [,]的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!