Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.82 KB | None | 0 0
  1. // 2020/4/22(水)
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Gyoretsu5 {
  6. public static void main(String[] args) {
  7. System.out.println("2つの行列の積を求めます");
  8.  
  9. System.out.println("\n行列Aを入力します");
  10. double[][] matrixA = inputMatrix();
  11. System.out.println("行列Aを出力します");
  12. printMatrix(matrixA);
  13.  
  14. System.out.println("\n行列Bを入力します");
  15. double[][] matrixB = inputMatrix();
  16. System.out.println("行列Bを出力します");
  17. printMatrix(matrixB);
  18.  
  19. System.out.println("\n積ABを計算します");
  20. double[][] matrixAB = multiplyMatrix(matrixA, matrixB);
  21. System.out.println("積ABを出力します");
  22. printMatrix(matrixAB);
  23.  
  24. System.out.println("\n積BAを計算します");
  25. double[][] matrixBA = multiplyMatrix(matrixB, matrixA);
  26. System.out.println("積BAを出力します");
  27. printMatrix(matrixBA);
  28. }
  29.  
  30. public static double[][] inputMatrix() {
  31. Scanner scanner = new Scanner(System.in);
  32. System.out.println("行列の行の大きさを自然数で入力して下さい");
  33. int row = scanner.nextInt();
  34. System.out.println("行列の列の大きさを自然数で入力して下さい");
  35. int column = scanner.nextInt();
  36. double[][] matrix = new double[row][column];
  37. for (int i = 0; i < row; i++) {
  38. for (int j = 0; j < column; j++) {
  39. System.out.println("行列の" + (i + 1) + "行" + (j + 1) + "列の要素の値(実数)を入力して下さい");
  40. matrix[i][j] = scanner.nextDouble();
  41. }
  42. }
  43. return matrix;
  44. }
  45.  
  46. public static void printMatrix(double[][] matrix) {
  47. if (matrix == null) {
  48. System.out.println("表示はありません");
  49. return;
  50. }
  51. for (int i = 0; i < matrix.length; i++) {
  52. for (int j = 0; j < matrix[0].length; j++) {
  53. System.out.print(matrix[i][j] + " ");
  54. }
  55. System.out.println();
  56. }
  57. }
  58.  
  59. public static double[][] multiplyMatrix(double[][] matrix1, double[][] matrix2) {
  60. if (matrix1[0].length != matrix2.length) {
  61. System.out.println("この2つの行列はこの順では積が求められません");
  62. return null;
  63. }
  64. double[][] product = new double[matrix1.length][matrix2[0].length];
  65. for (int i = 0; i < matrix1.length; i++) {
  66. for (int j = 0; j < matrix2[0].length; j++) {
  67. for (int k = 0; k < matrix1[0].length /* matrix2.lengthでも同じ */ ; k++) {
  68. product[i][j] += matrix1[i][k] * matrix2[k][j];
  69. }
  70. }
  71. }
  72. return product;
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement