简体   繁体   English

将二维数组矩阵转换为单位矩阵C#

[英]Converting a 2D Array Matrix into an identity matrix c#

I am supposed to create a button that will convert an already existing 2D array matrix into an identity matrix. 我应该创建一个按钮,将一个已经存在的2D数组矩阵转换为一个单位矩阵。 Obviously you need to make sure the amount of columns and rows are the same in the original matrix in order to make it an identity matrix but I'm a little confused on how to go about doing this. 显然,您需要确保原始矩阵中的列和行的数量相同,才能使其成为一个单位矩阵,但是我对如何执行此操作感到有些困惑。

So far, I have: 到目前为止,我有:

        private void btnMakeBIdentity_Click(object sender, EventArgs e)
    {
        double[,] identityMatrixB = new double[matrixBRows, matrixBCols];
        if(matrixBRows == matrixBCols)
        {
            identityMatrixB = IdentityMatrix(matrixBRows);
        }
        matrixB = identityMatrixB;

        matrixToString(matrixB, txtFullMatrixB);
    }

And the method matrixToString: 和方法matrixToString:

        private double[,] IdentityMatrix(int n)
     {
        double[,] result = createMatrix(n, n);
        for (int i = 0; i < n; ++i)
            result[i,i] = 1.0;
        return result;
     }

In this code: matrixB, matrixBRows, matrixBCols are all global variables of the class. 在此代码中:matrixB,matrixBRows,matrixBCols都是该类的全局变量。 Matrix B was created using: 矩阵B是使用以下方法创建的:

        private void btnCreateMatrixB_Click(object sender, EventArgs e)
    {
        try
        {
            matrixBRows = Convert.ToInt32(txtMatrixBRows.Text);
            matrixBCols = Convert.ToInt32(txtMatrixBCols.Text);

        }
        catch (Exception ex)
        {
            MessageBox.Show("Please check the textboxes for Matrix B's rows and columns. Be sure you are inputing a valid integer.");
        }

        matrixB = createMatrix(matrixBRows, matrixBCols);
        matrixToString(matrixB, txtFullMatrixB);


    }

An example of output that is given after Matrix B created would be: 创建矩阵B之后给出的输出示例为:

8.3   10   5.2   
0.1   6.3   7.8   
7.6   1.3   1.1   

after running IdentityMatrix after clicking "Make Matrix B Identity" I get: 在单击“ Make Matrix B Identity”后运行IdentityMatrix后,我得到:

1.0   10   5.2   
0.1   1.0   7.8   
7.6   1.3   1.0

Any help or suggestions would be awesome. 任何帮助或建议都会很棒。 Thanks! 谢谢!

You have to set the other elements to 0. So you could do something like this: 您必须将其他元素设置为0。因此您可以执行以下操作:

for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
        if (i == j)
            result[i,j] = 1.0;
        else result[i,j] = 0.0;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM