如何将矩阵 int[,] 的值从左下角到右上角对角相加?

发布于 2024-08-23 20:07:23 字数 398 浏览 2 评论 0原文

如何将矩阵 int[,] 的值从左下角到右上角对角相加?

我试图帮助朋友理解这一点,但即使我也不太明白他们在这里做什么。

这是我试图向他解释的方法:

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];
            }
        }
    }
}

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];
            }
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

记忆里有你的影子 2024-08-30 20:07:23

理解这一点的关键是 if 语句:

if (f == columnas - c - 1)

两个嵌套循环在行上迭代(使用 f 作为索引),并在每行上迭代列(使用 c 作为索引)。

因此,每次迭代,您都会测试行号(即 f)是否等于反转的列号(即从总列数 - columnas)。测试列号反转的原因是因为您想要从左下角到右上角添加,这与从右上角到左下角添加相同。

需要注意的一件事是,矩阵对角线仅对方阵有意义,这意味着列数需要与行数相同(在您的算法中 filas 应等于 columnas< /代码>)。

因此,假设一个 5x5 矩阵:

第 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)

The key to understanding this is the if statement:

if (f == columnas - c - 1)

The two nested loops iterate over rows (using f as an index) and for each row, over columns (using c as an index).

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.

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).

So, assuming a 5x5 matrix:

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)

不喜欢何必死缠烂打 2024-08-30 20:07:23

不需要双循环。

mxm 矩阵:

for(int rowNr = 0; rowNr < m; rowNr++)
{
   int colNr = m - rowNr - 1;
   Addition += matrix[rownr, colnr];
}

There's no need for a double loop.

m x m matrix:

for(int rowNr = 0; rowNr < m; rowNr++)
{
   int colNr = m - rowNr - 1;
   Addition += matrix[rownr, colnr];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文