0

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!

1 Answer 1

4

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Literally as soon as I uploaded this question, I had this idea... Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.