簡體   English   中英

將二維數組矩陣轉換為單位矩陣C#

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

我應該創建一個按鈕,將一個已經存在的2D數組矩陣轉換為一個單位矩陣。 顯然,您需要確保原始矩陣中的列和行的數量相同,才能使其成為一個單位矩陣,但是我對如何執行此操作感到有些困惑。

到目前為止,我有:

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

和方法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;
     }

在此代碼中:matrixB,matrixBRows,matrixBCols都是該類的全局變量。 矩陣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);


    }

創建矩陣B之后給出的輸出示例為:

8.3   10   5.2   
0.1   6.3   7.8   
7.6   1.3   1.1   

在單擊“ Make Matrix B Identity”后運行IdentityMatrix后,我得到:

1.0   10   5.2   
0.1   1.0   7.8   
7.6   1.3   1.0

任何幫助或建議都會很棒。 謝謝!

您必須將其他元素設置為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