如何在Java中用矩陣元素的平方替換矩陣元素?


矩陣不僅僅是資料的集合,它還是一個以二維矩形佈局排列的資料元素的集合。在Java中,一個二維陣列可以被視為一個矩陣。

根據問題陳述,任務是用其平方替換矩陣元素。

讓我們深入探討本文,瞭解如何使用Java程式語言來實現它。

為您展示一些例項

例項1

假設原始矩陣為{{8,3,2}, {12,7,9}, {6,4,10}};

用其平方替換矩陣元素後,結果矩陣將為

64 9 4
144 49 81
36 16 100

例項2

假設原始矩陣為{{4,3,7}, {2,3,9}, {3,4,9}};

用其平方替換矩陣元素後,結果矩陣將為

16 9 49
4 9 81
9 16 81

例項3

假設原始矩陣為{{1,2,3}, {2,1,3}, {3,2,1}};

用其平方替換矩陣元素後,結果矩陣將為

1 4 9
4 1 9
9 4 1

演算法

步驟1 - 初始化並宣告矩陣。

步驟2 - 建立另一個矩陣來儲存平方值。

步驟3 - 將矩陣元素自身相乘或使用內建的pow()函式獲取平方。

步驟4 - 列印結果。

語法

為了獲得Java中任何數的另一個數次冪,我們有內建的java.lang.Math.pow()方法

以下是使用該方法獲取2的次冪的語法:

double power = math.pow (inputValue,2)

多種方法

我們提供了多種解決方法。

  • 使用帶pow()函式的矩陣靜態初始化。

  • 使用不帶內建函式的使用者自定義方法。

讓我們逐一檢視程式及其輸出。

方法1:使用帶pow()函式的矩陣靜態初始化

在此方法中,矩陣元素將在程式中初始化。然後根據演算法,用其平方替換矩陣元素。這裡我們將使用內建的Pow()函式來獲取元素的平方。

示例

public class Main {

   //main method
   public static void main(String args[]){

      //Initialising the matrix
      int a[][]={{8,3,2},{12,7,9},{6,4,10}};

      //creating another matrix to store the square value
      int c[][]=new int[3][3];

      //Multiplying the matrix element by itself to get the square
      for(int i=0;i<3;i++){
         for(int j=0;j<3;j++){
         int element = a[i][j];
            c[i][j]+= Math.pow(element,2);

            //printing the result
            System.out.print(c[i][j]+" ");

         }//end of j loop

         //new line
         System.out.println();

      }//end of i loop
   }
}

輸出

64 9 4 
144 49 81 
36 16 100

方法2:使用不帶內建函式的使用者自定義方法

在此方法中,矩陣元素將在程式中初始化。然後透過傳遞矩陣作為引數來呼叫使用者自定義方法,並在方法內部根據演算法用其平方替換矩陣元素。這裡,我們將元素自身相乘以獲取元素的平方。

示例

public class Main {
   //main method
   public static void main(String args[]){
     
     //Initialising the matrix
      int a[][]={{4,3,7},{2,3,9},{3,4,9}};
     
     //calling user defined method
      square(a);
   }

   //user defined method
   static void square(int a[][]) {

      //creating another matrix to store the square value
      int c[][]=new int[3][3];

      //Multiplying the matrix element by itself to get the square
      for(int i=0;i<3;i++){
         for(int j=0;j<3;j++){
            c[i][j]+=a[i][j] * a[i][j];

            //printing the result
            System.out.print(c[i][j]+" ");
         }//end of j loop
        
         //new line
         System.out.println();
      }//end of i loop
   }
}

輸出

16 9 49 
4 9 81 
9 16 81

在本文中,我們探討了使用Java程式語言用其平方替換矩陣元素的不同方法。

更新於: 2023年3月9日

687 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.