web-dev-qa-db-fra.com

Multiplication matricielle à l'aide de tableaux

J'essaie de créer une méthode de multiplication matricielle simple à l'aide de tableaux multidimensionnels ([2][2]). Je suis un peu nouveau dans ce domaine et je n'arrive pas à trouver ce que je fais de travers. J'apprécierais vraiment toute aide pour me dire ce que c'est. Je préférerais ne pas utiliser les bibliothèques ou quoi que ce soit du genre, je fais surtout cela pour apprendre comment cela fonctionne. Merci d'avance.

Je déclare mes tableaux dans la méthode principale comme suit:

Double[][] A={{4.00,3.00},{2.00,1.00}}; 
Double[][] B={{-0.500,1.500},{1.000,-2.0000}};

A * B devrait retourner la matrice d'identité. Ce n'est pas.

public static Double[][] multiplicar(Double[][] A, Double[][] B){
//the method runs and returns a matrix of the correct dimensions
//(I actually changed the .length function to a specific value to eliminate 
//it as a possible issue), but not the correct values

    Double[][] C= new Double[2][2];
    int i,j;

    ////I fill the matrix with zeroes, if I don't do this it gives me an error
    for(i=0;i<2;i++) {
        for(j=0;j<2;j++){
            C[i][j]=0.00000;
        }
    } 
    ///this is where I'm supposed to perform the adding of every element in
    //a row of A multiplied by the corresponding element in the
    //corresponding column of B, for all columns in B and all rows in A
    for(i=0;i<2;i++){
        for(j=0;j<2;j++)
            C[i][j]+=(A[i][j]*B[j][i]);
    }
    return C;
}
27
user2577854

Vous pouvez essayer ce code:

public class MyMatrix {
    Double[][] A = { { 4.00, 3.00 }, { 2.00, 1.00 } };
    Double[][] B = { { -0.500, 1.500 }, { 1.000, -2.0000 } };

    public static Double[][] multiplicar(Double[][] A, Double[][] B) {

        int aRows = A.length;
        int aColumns = A[0].length;
        int bRows = B.length;
        int bColumns = B[0].length;

        if (aColumns != bRows) {
            throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + ".");
        }

        Double[][] C = new Double[aRows][bColumns];
        for (int i = 0; i < aRows; i++) {
            for (int j = 0; j < bColumns; j++) {
                C[i][j] = 0.00000;
            }
        }

        for (int i = 0; i < aRows; i++) { // aRow
            for (int j = 0; j < bColumns; j++) { // bColumn
                for (int k = 0; k < aColumns; k++) { // aColumn
                    C[i][j] += A[i][k] * B[k][j];
                }
            }
        }

        return C;
    }

    public static void main(String[] args) {

        MyMatrix matrix = new MyMatrix();
        Double[][] result = multiplicar(matrix.A, matrix.B);

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++)
                System.out.print(result[i][j] + " ");
            System.out.println();
        }
    }
}
28
amatellanes

Java. Multiplication matricielle.

Testé avec des matrices de taille différente.

public class Matrix {

/**
 * Matrix multiplication method.
 * @param m1 Multiplicand
 * @param m2 Multiplier
 * @return Product
 */
    public static double[][] multiplyByMatrix(double[][] m1, double[][] m2) {
        int m1ColLength = m1[0].length; // m1 columns length
        int m2RowLength = m2.length;    // m2 rows length
        if(m1ColLength != m2RowLength) return null; // matrix multiplication is not possible
        int mRRowLength = m1.length;    // m result rows length
        int mRColLength = m2[0].length; // m result columns length
        double[][] mResult = new double[mRRowLength][mRColLength];
        for(int i = 0; i < mRRowLength; i++) {         // rows from m1
            for(int j = 0; j < mRColLength; j++) {     // columns from m2
                for(int k = 0; k < m1ColLength; k++) { // columns from m1
                    mResult[i][j] += m1[i][k] * m2[k][j];
                }
            }
        }
        return mResult;
    }

    public static String toString(double[][] m) {
        String result = "";
        for(int i = 0; i < m.length; i++) {
            for(int j = 0; j < m[i].length; j++) {
                result += String.format("%11.2f", m[i][j]);
            }
            result += "\n";
        }
        return result;
    }

    public static void main(String[] args) {
        // #1
        double[][] multiplicand = new double[][] {
                {3, -1, 2},
                {2,  0, 1},
                {1,  2, 1}
        };
        double[][] multiplier = new double[][] {
                {2, -1, 1},
                {0, -2, 3},
                {3,  0, 1}
        };
        System.out.println("#1\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
        // #2
        multiplicand = new double[][] {
                {1, 2, 0},
                {-1, 3, 1},
                {2, -2, 1}
        };
        multiplier = new double[][] {
                {2},
                {-1},
                {1}
        };
        System.out.println("#2\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
        // #3
        multiplicand = new double[][] {
                {1, 2, -1},
                {0,  1, 0}
        };
        multiplier = new double[][] {
                {1, 1, 0, 0},
                {0, 2, 1, 1},
                {1, 1, 2, 2}
        };
        System.out.println("#3\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
    }
}

Sortie:

#1
      12.00      -1.00       2.00
       7.00      -2.00       3.00
       5.00      -5.00       8.00

#2
       0.00
      -4.00
       7.00

#3
       0.00       4.00       0.00       0.00
       0.00       2.00       1.00       1.00
10
Dmytro Dzyubak
static int b[][]={{21,21},{22,22}};

static int a[][] ={{1,1},{2,2}};

public static void mul(){
    int c[][] = new int[2][2];

    for(int i=0;i<b.length;i++){
        for(int j=0;j<b.length;j++){
            c[i][j] =0;
        }   
    }

    for(int i=0;i<a.length;i++){
        for(int j=0;j<b.length;j++){
            for(int k=0;k<b.length;k++){
            c[i][j]= c[i][j] +(a[i][k] * b[k][j]);
            }
        }
    }

    for(int i=0;i<c.length;i++){
        for(int j=0;j<c.length;j++){
            System.out.print(c[i][j]);
        }   
        System.out.println("\n");
    }
}
5
Sivakumar Kuppusamy

Essaye ça,

public static Double[][] multiplicar(Double A[][],Double B[][]){
    Double[][] C= new Double[2][2];
    int i,j,k;
     for (i = 0; i < 2; i++) {
         for (j = 0; j < 2; j++) {
             C[i][j] = 0.00000;
         }
     }
    for(i=0;i<2;i++){
        for(j=0;j<2;j++){
            for (k=0;k<2;k++){
                  C[i][j]+=(A[i][k]*B[k][j]);

            }

        }
    }
    return C;
}
2
Dulanga

essayez ceci, cela peut vous aider

import Java.util.Scanner;

public class MulTwoArray {

public static void main(String[] args) {

    int i, j, k;
    int[][] a = new int[3][3];
    int[][] b = new int[3][3];
    int[][] c = new int[3][3];



    Scanner sc = new Scanner(System.in);

    System.out.println("Enter size of array a");
    int rowa = sc.nextInt();
    int cola = sc.nextInt();

    System.out.println("Enter size of array b");
    int rowb = sc.nextInt();
    int colb = sc.nextInt();


    //read and b

    System.out.println("Enter elements of array a");
    for (i = 0; i < rowa; ++i) {
        for (j = 0; j < cola; ++j) {

            a[i][j] = sc.nextInt();

        }
        System.out.println();
    }
    System.out.println("Enter elements of array b");
    for (i = 0; i < rowb; ++i) {
        for (j = 0; j < colb; ++j) {

            b[i][j] = sc.nextInt();

        }
        System.out.println("\n");
    }

    //print a and b

    System.out.println("the elements of array a");
    for (i = 0; i < rowa; ++i) {
        for (j = 0; j < cola; ++j) {

            System.out.print(a[i][j]);
            System.out.print("\t");

        }
        System.out.println("\n");
    }
    System.out.println("the elements of array b");
    for (i = 0; i < rowb; ++i) {
        for (j = 0; j < colb; ++j) {

            System.out.print(b[i][j]);
            System.out.print("\t");

        }
        System.out.println("\n");

    }

    //multiply a and b

    for (i = 0; i < rowa; ++i) {

        for (j = 0; j < colb; ++j) {
            c[i][j] = 0;
            for (k = 0; k < cola; ++k) {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }


    //print multi result

    System.out.println("result of multiplication of array a and b is ");
    for (i = 0; i < rowa; ++i) {
        for (j = 0; j < colb; ++j) {

            System.out.print(c[i][j]);
            System.out.print("\t");
        }
        System.out.println("\n");
    }
}
}
1
Ragataj

La méthode mults est une procédure (Pascal) ou un sous-programme (Fortran)

La méthode multMatrix est une fonction (Pascal, Fortran)

import Java.util.*;

public class MatmultE
{
private static Scanner sc = new Scanner(System.in);
  public static void main(String [] args)
  {
    double[][] A={{4.00,3.00},{2.00,1.00}}; 
    double[][] B={{-0.500,1.500},{1.000,-2.0000}};
    double[][] C=multMatrix(A,B);
    printMatrix(A);
    printMatrix(B);    
    printMatrix(C);

    double a[][] = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
    double b[][] = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
    double[][] c=multMatrix(a,b);
    printMatrix(a);
    printMatrix(b);    
    printMatrix(c);

    double[][] a1 = readMatrix();
    double[][] b1 = readMatrix();
    double[][] c1 = new double[a1.length][b1[0].length];
    mults(a1,b1,c1,a1.length,a1[0].length,b1.length,b1[0].length);
    printMatrix(c1);
    printMatrixE(c1);
  }

   public static double[][] readMatrix() {
       int rows = sc.nextInt();
       int cols = sc.nextInt();
       double[][] result = new double[rows][cols];
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < cols; j++) {
              result[i][j] = sc.nextDouble();
           }
       }
       return result;
   }


  public static void printMatrix(double[][] mat) {
  System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
       int rows = mat.length;
       int columns = mat[0].length;
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               System.out.printf("%8.3f " , mat[i][j]);
           }
           System.out.println();
       }
   System.out.println();
  }

  public static void printMatrixE(double[][] mat) {
  System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
       int rows = mat.length;
       int columns = mat[0].length;
       for (int i = 0; i < rows; i++) {
           for (int j = 0; j < columns; j++) {
               System.out.printf("%9.2e " , mat[i][j]);
           }
           System.out.println();
       }
   System.out.println();
  }


   public static double[][] multMatrix(double a[][], double b[][]){//a[m][n], b[n][p]
   if(a.length == 0) return new double[0][0];
   if(a[0].length != b.length) return null; //invalid dims

   int n = a[0].length;
   int m = a.length;
   int p = b[0].length;

   double ans[][] = new double[m][p];

   for(int i = 0;i < m;i++){
      for(int j = 0;j < p;j++){
         ans[i][j]=0;
         for(int k = 0;k < n;k++){
            ans[i][j] += a[i][k] * b[k][j];
         }
      }
   }
   return ans;
   }

   public static void mults(double a[][], double b[][], double c[][], int r1, 
                        int c1, int r2, int c2){
      for(int i = 0;i < r1;i++){
         for(int j = 0;j < c2;j++){
            c[i][j]=0;
            for(int k = 0;k < c1;k++){
               c[i][j] += a[i][k] * b[k][j];
            }
         }
      }
   }
}

où en tant que matrice d'entrée vous pouvez entrer 

inE.txt

4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.0 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0

dans unix, comme cmmd line, exécutez la commande:

$ Java MatmultE <inE.txt> outE.txt

et vous obtenez la sortie

outC.txt

Matrix[2][2]
   4.000    3.000 
   2.000    1.000 

Matrix[2][2]
  -0.500    1.500 
   1.000   -2.000 

Matrix[2][2]
   1.000    0.000 
   0.000    1.000 

Matrix[3][4]
   1.000    2.000   -2.000    0.000 
  -3.000    4.000    7.000    2.000 
   6.000    0.000    3.000    1.000 

Matrix[4][2]
  -1.000    3.000 
   0.000    9.000 
   1.000  -11.000 
   4.000   -5.000 

Matrix[3][2]
  -3.000   43.000 
  18.000  -60.000 
   1.000  -20.000 

Matrix[4][3]
  -7.000   15.000    3.000 
 -36.000   70.000   20.000 
-105.000  189.000   57.000 
-256.000  420.000   96.000 

Matrix[4][3]
-7.00e+00  1.50e+01  3.00e+00 
-3.60e+01  7.00e+01  2.00e+01 
-1.05e+02  1.89e+02  5.70e+01 
-2.56e+02  4.20e+02  9.60e+01 
1
Andrei

importer Java.util. *; public class Mult {

public static int[][] C;

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);

    System.out.println("Enter Row of Matrix A");
    int Rowa = s.nextInt();

    System.out.println("Enter Column of Matrix A");
    int Cola = s.nextInt();

    System.out.println("Enter Row of Matrix B");
    int Rowb = s.nextInt();

    System.out.println("Enter Column of Matrix B");
    int Colb = s.nextInt();

    int[][] A = new int[Rowa][Cola];
    int[][] B = new int[Rowb][Colb];

    C= new int[Rowa][Colb];
    //int[][] C = new int;
    System.out.println("Enter Values of Matrix A");

    for(int i =0 ; i< A.length ; i++) {
        for(int j = 0 ; j<A.length;j++) {
            A[i][j] = s.nextInt();
        }

    }

    System.out.println("Enter Values of Matrix B");

    for(int i =0 ; i< B.length ; i++) {
        for(int j = 0 ; j<B.length;j++) {
            B[i][j] = s.nextInt();
        }
    }




    if(Cola==Rowb) {
        for(int i = 0;i < A.length;i++){
              for(int j = 0;j < A.length;j++){
                 C[i][j]=0;
                 for(int k = 0;k < B.length;k++){
                    C[i][j] += A[i][k] * B[k][j];
                 }
              }
           }
    }
    else {
        System.out.println("Cannot multiply");
    }









    // Printing matrix A
    /*
    for(int i =0 ; i< A.length ; i++) {
        for(int j = 0 ; j<A.length;j++) {
        System.out.print(A[i][j]+ "\t");
        }
        System.out.println();
    }
    */

    for(int i =0 ; i< A.length ; i++) {
        for(int j = 0 ; j<A.length;j++) {
        System.out.print(C[i][j]+ "\t");
        }
        System.out.println();
    }

}

}

0
Arsalan Bajwa