Java >> Tutoriel Java >  >> Java

Programme Java pour effectuer une multiplication matricielle

Dans ce tutoriel, nous allons apprendre à effectuer une multiplication matricielle. Mais avant d'aller plus loin, si vous n'êtes pas familier avec les concepts du tableau, alors consultez l'article Tableaux en Java.

Vous trouverez ci-dessous la représentation picturale de la même chose.

Entrée :

Entrez le nombre de lignes dans la première matrice :3

Entrez le nombre de colonnes dans la première matrice :3

Saisissez le nombre de lignes dans la seconde matrice :3

Saisissez le nombre de lignes dans la seconde matrice :3

Saisissez tous les éléments de la première matrice :1 2 3 4 5 6 7 8 9

Entrez tous les éléments de la deuxième matrice :9 8 7 6 5 4 3 2 1

Sortie :

Première matrice :

1 2 3

4 5 6

7 8 9

Deuxième matrice :

9 8 7

6 5 4

3 2 1

Matrice résultante :

30 24 18

84 69 54

138 114 90

Programme 1 :effectuer une multiplication matricielle

Dans ce programme, nous allons effectuer une multiplication matricielle. Mais pour que la multiplication matricielle ait lieu, le nombre de colonnes de la première matrice doit être égal au nombre de lignes de la seconde matrice.

Algorithme

  1. Démarrer
  2. Déclarez des variables pour la taille de la matrice.
  3. Initialiser le nombre de lignes et de colonnes pour la première matrice.
  4. Initialiser le nombre de lignes et de colonnes pour la deuxième matrice.
  5. Déclarez deux matrices.
  6. Demandez à l'utilisateur d'initialiser les matrices.
  7. Appelez une méthode pour multiplier les deux matrices.
  8. Imprimez les deux matrices.
  9. Vérifiez si la multiplication matricielle est possible ou non.
  10. Si possible, créez une nouvelle matrice pour stocker le produit des deux matrices.
  11. Parcourez chaque élément des deux matrices et multipliez-les.
  12. Stocker ce produit dans la nouvelle matrice à l'index correspondant.
  13. Imprimez la matrice du produit final.
  14. Si la multiplication matricielle n'est pas possible, alors affichez-la.
  15. Arrêtez.

Vous trouverez ci-dessous le code correspondant en langage Java.

/*Java Program to multiply two matrices*/
import java.util.Scanner;
public class Main
{
   // To print Matrix 
    static void printMatrix(int M[][], int rowSize, int colSize) 
    { 
        for (int i = 0; i < rowSize; i++) 
        { 
            for (int j = 0; j < colSize; j++) 
            {
                System.out.print(M[i][j] + " "); 
            }
  
            System.out.println(); 
        } 
    }   
    // To multiply two matrices a[][] and b[][] 
    static void multiplyMatrix(int p,int q, int a[][], int m, int n, int b[][]) 
    { 
        int i, j, k;   
        // Print the matrices A and B 
        System.out.println("First Matrix:");
        printMatrix(a, p, q); 
        System.out.println("Second Matrix:");
        printMatrix(b, m, n);   
        // Check if multiplication is Possible 
        if (m != q) 
        { 
            System.out.println("Multiplication Not Possible"); 
            return; 
        }   
        // Matrix to store the result 
        int c[][] = new int[q][n]; 
  
        // Multiply the two matrices 
        for (i = 0; i < p; i++) 
        { 
            for (j = 0; j < n; j++) 
            { 
                for (k = 0; k < m; k++) 
                    c[i][j] += a[i][k] * b[k][j]; 
            } 
        }   
        // Print the result 
        System.out.println("\nResultant Matrix:"); 
        printMatrix(c, p, n); 
    }   
   //Driver Code
    public static void main(String[] args) 
    {
        int p, q, m, n;    //Declare matrix size
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows in the first matrix:");
        p = sc.nextInt();    //Initialize first matrix size
        System.out.print("Enter the number of columns in the first matrix:");
        q = sc.nextInt();   //Initialize first matrix size
        System.out.print("Enter the number of rows in the second matrix:");
        m = sc.nextInt();   //Initialize second matrix size
        System.out.print("Enter the number of columns in the second matrix:");
        n = sc.nextInt();   //Initialize second matrix size
        int a[][] = new int[p][q];    //Declare first matrix
        int b[][] = new int[m][n];    //Declare second matrix            
            //Initialize the first Matrix
            System.out.println("Enter all the elements of first matrix:");
            for (int i = 0; i < p; i++) 
            {
                for (int j = 0; j < q; j++) 
                {
                    a[i][j] = sc.nextInt();
                }
            }
            System.out.println("");
            
            //Initialize the second matrix
            System.out.println("Enter all the elements of second matrix:");
            for (int i = 0; i < m; i++) 
            {
                for (int j = 0; j < n; j++) 
                {
                    b[i][j] = sc.nextInt();
                }
            }            
            //To Multiply two matrices
             multiplyMatrix(p ,q, a, m, n, b);    
    }
}


Entrez le nombre de lignes dans la première matrice :3
Entrez le nombre de colonnes dans la première matrice :3
Entrez le nombre de lignes dans la deuxième matrice :3
Entrez nombre de colonnes dans la seconde matrice :3
Saisir tous les éléments de la première matrice :1 2 3 4 5 6 5 4 3

Saisir tous les éléments de la deuxième matrice :6 5 4 7 1 2 3 4 5
Première matrice :
1 2 3
4 5 6
5 4 3
Deuxième matrice :
6 5 4
/>7 1 2
3 4 5

Matrice résultante :
29 19 23
77 49 56
67 41 43

Programme 2 :effectuer une multiplication matricielle

Dans ce programme, nous allons effectuer une multiplication matricielle. La multiplication matricielle est une opération binaire simple qui produit une seule matrice à partir des deux matrices données. Lorsque deux matrices d'ordre m*n et n*p sont multipliées, la matrice résultante sera d'ordre m*p.

Algorithme

  1. Démarrer
  2. Déclarez des variables pour la taille de la matrice.
  3. Initialiser le nombre de lignes et de colonnes pour la première matrice.
  4. Initialiser le nombre de lignes et de colonnes pour la deuxième matrice.
  5. Déclarez deux matrices.
  6. Demandez à l'utilisateur d'initialiser les matrices.
  7. Imprimez les deux matrices.
  8. Vérifiez si la multiplication matricielle est possible ou non.
  9. Si possible, créez une nouvelle matrice pour stocker le produit des deux matrices.
  10. Parcourez chaque élément des deux matrices et multipliez-les.
  11. Stocker ce produit dans la nouvelle matrice à l'index correspondant.
  12. Imprimez la matrice du produit final.
  13. Si la multiplication matricielle n'est pas possible, alors affichez-la.
  14. Arrêtez.

Vous trouverez ci-dessous le code correspondant en langage Java.

/*Java Program to multiply two matrices*/
import java.util.Scanner;
public class Main
{
   //Driver Code
    public static void main(String[] args) 
    {
        //Take input from user
        Scanner sc = new Scanner(System.in);        
        int p, q, m, n;    //Declare matrix size
        System.out.print("Enter the number of rows in the first matrix:");
        p = sc.nextInt();    //Initialize the the first matrix size
        System.out.print("Enter number of columns in the first matrix:");
        q = sc.nextInt();   //Initialize first matrix size
        System.out.print("Enter the number of rows in the second matrix:");
        m = sc.nextInt();   //Initialize second matrix size
        System.out.print("Enter the number of columns in the second matrix:");
        n = sc.nextInt();   //Initialize second matrix size
        
         int a[][] = new int[p][q];    //Declare first matrix
            int b[][] = new int[m][n];    //Declare second matrix            
            //Initialize the first Matrix
            System.out.println("Enter all the elements of first matrix:");
            for (int i = 0; i < p; i++) 
            {
                for (int j = 0; j < q; j++) 
                {
                    a[i][j] = sc.nextInt();
                }
            }
            System.out.println("");            
            //Initialize the second matrix
            System.out.println("Enter all the elements of second matrix:");
            for (int i = 0; i < m; i++) 
            {
                for (int j = 0; j < n; j++) 
                {
                    b[i][j] = sc.nextInt();
                }
            }            
            //Print the First Matrix
            System.out.println("First Matrix:");
            for(int i=0;i<p;i++)
            {
                for(int j=0;j<q;j++)
                {
                    System.out.print(a[i][j]+" ");
                }
                System.out.println("");
            }            
            //Print Second Matrix
            System.out.println("Second Matrix:");
            for(int i=0;i<m;i++)
            {
                for(int j=0;j<n;j++)
                {
                    System.out.print(b[i][j]+" ");
                }
                System.out.println("");
            }                      
        // Check if multiplication is Possible 
        if (m != q) { 
  
            System.out.println("Multiplication Not Possible"); 
            return; 
        }   
        // Matrix to store the result 
        int c[][] = new int[q][n]; 
        int k=0;
  
        // Multiply the two matrices 
        for(int i=0;i<p;i++)
        { 
            for(int j=0;j<n;j++)
            { 
                for (k = 0; k < m; k++) 
                    c[i][j] += a[i][k] * b[k][j]; 
            } 
        }   
        // Print the resultant matrix
        System.out.println("Resultant Matrix:"); 
        for(int i=0;i<q;i++)
            {
                for(int j=0;j<n;j++)
                {
                    System.out.print(c[i][j]+" ");
                }
                System.out.println("");
            }   
    }
}


Entrez le nombre de lignes dans la première matrice :3
Entrez le nombre de colonnes dans la première matrice :3
Entrez le nombre de lignes dans la deuxième matrice :3
Entrez le nombre de colonnes de la deuxième matrice :3
Saisir tous les éléments de la première matrice :1 2 3 4 5 6 7 8 9
Saisir tous les éléments de la deuxième matrice :3 4 5 2 6 7 1 2 1
Première matrice :
1 2 3
4 5 6
7 8 9
Deuxième matrice :
3 4 5
2 6 7
1 2 1
Matrice résultante :
10 22 22
28 58 61
46 94 100


Balise Java