简体   繁体   中英

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

        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. Matrix B was created using:

        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:

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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