programa Java para multiplicar dos matrices

En este programa java, vamos a aprender cómo encontrar multiplicación de dos matrices ? Aquí, estamos tomando la entrada de dos matrices e imprimir su multiplicación.

Dadas dos matrices y encontrar su multiplicación en tercera matriz e imprimir la matriz mediante el programa Java.

Ejemplo:

Input (Matrix 1)
25 52
65 85
Input (Matrix 2)
96 65
36 85
Output (Multiplication Matrix)
4272 6045
9300 11450

programa para encontrar la multiplicación de matrices utilizando el programa java

import java.util.Scanner;
public class MatrixMultiplication
{
public static void main(String args[])
{
int n;
//object of scanner class
Scanner input = new Scanner(System.in);
//input base (number of rows and cols)
System.out.print("Enter the base the matrices : ");
n = input.nextInt();
//create two_D array (matrix) objects
int[][] a = new int[n][n];
int[][] b = new int[n][n];
int[][] c = new int[n][n];
//input matrix 1
System.out.println("Enter the elements of 1st Matrix row wise n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = input.nextInt();
}
}
//input matrix 2
System.out.println("Enter the elements of 2nd mrtix row wise n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
b[i][j] = input.nextInt();
}
}
//multiplication logic
System.out.println("Multiplying both sthe matrices...");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
//print final/result matrix
System.out.println("The product of the matrices is : ");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
input.close();
}
}

salida 1

Enter the base the matrices : 5
Enter the elements of 1st Matrix row wise
12 45 56 85 25
12 41 20 25 65
36 54 52 58 68
32 12 20 12 32
45 87 45 65 35
Enter the elements of 2nd Matrix row wise
45 65 25 35 14
12 12 12 12 12
32 31 36 35 34
52 51 58 57 59
63 65 69 68 64
Multiplying both the matrices...
The product of the matrices is :
8867 9016 9511 9465 9227
7067 7392 7447 7457 6975
11232 11978 11476 11658 10694
4864 5536 4568 4824 4028
10094 10954 9974 10279 9279

salida 2

Enter the base the matrices : 2
Enter the elements of 1st Matrix row wise
25 52
65 85
Enter the elements of 2nd Matrix row wise
96 65
36 85
Multiplying both the matrices...
The product of the matrices is :
4272 6045
9300 11450


Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *