Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 2020/4/22(水)
- import java.util.Scanner;
- public class Gyoretsu5 {
- public static void main(String[] args) {
- System.out.println("2つの行列の積を求めます");
- System.out.println("\n行列Aを入力します");
- double[][] matrixA = inputMatrix();
- System.out.println("行列Aを出力します");
- printMatrix(matrixA);
- System.out.println("\n行列Bを入力します");
- double[][] matrixB = inputMatrix();
- System.out.println("行列Bを出力します");
- printMatrix(matrixB);
- System.out.println("\n積ABを計算します");
- double[][] matrixAB = multiplyMatrix(matrixA, matrixB);
- System.out.println("積ABを出力します");
- printMatrix(matrixAB);
- System.out.println("\n積BAを計算します");
- double[][] matrixBA = multiplyMatrix(matrixB, matrixA);
- System.out.println("積BAを出力します");
- printMatrix(matrixBA);
- }
- public static double[][] inputMatrix() {
- Scanner scanner = new Scanner(System.in);
- System.out.println("行列の行の大きさを自然数で入力して下さい");
- int row = scanner.nextInt();
- System.out.println("行列の列の大きさを自然数で入力して下さい");
- int column = scanner.nextInt();
- double[][] matrix = new double[row][column];
- for (int i = 0; i < row; i++) {
- for (int j = 0; j < column; j++) {
- System.out.println("行列の" + (i + 1) + "行" + (j + 1) + "列の要素の値(実数)を入力して下さい");
- matrix[i][j] = scanner.nextDouble();
- }
- }
- return matrix;
- }
- public static void printMatrix(double[][] matrix) {
- if (matrix == null) {
- System.out.println("表示はありません");
- return;
- }
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix[0].length; j++) {
- System.out.print(matrix[i][j] + " ");
- }
- System.out.println();
- }
- }
- public static double[][] multiplyMatrix(double[][] matrix1, double[][] matrix2) {
- if (matrix1[0].length != matrix2.length) {
- System.out.println("この2つの行列はこの順では積が求められません");
- return null;
- }
- double[][] product = new double[matrix1.length][matrix2[0].length];
- for (int i = 0; i < matrix1.length; i++) {
- for (int j = 0; j < matrix2[0].length; j++) {
- for (int k = 0; k < matrix1[0].length /* matrix2.lengthでも同じ */ ; k++) {
- product[i][j] += matrix1[i][k] * matrix2[k][j];
- }
- }
- }
- return product;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement