teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

multiplyメソッドを使うコードを追加

2021/07/05 10:01

投稿

kazuma-s
kazuma-s

スコア8222

answer CHANGED
@@ -69,4 +69,85 @@
69
69
  c.print();
70
70
  }
71
71
  }
72
+ ```
73
+ **追記**
74
+ 行列の掛け算をコンストラクタで実行するのではなく、
75
+ a.multiply(b) で結果の Matrix を返してくれるようにしてみました。
76
+ ```Java
77
+ import java.io.*;
78
+
79
+ public class Matrix {
80
+ private int row, col;
81
+ private double[][] matrix;
82
+
83
+ public Matrix() {}
84
+
85
+ public Matrix(int row, int col) {
86
+ this.row = row;
87
+ this.col = col;
88
+ matrix = new double[row][col];
89
+ }
90
+
91
+ public void read(String filename) {
92
+ try (BufferedReader br = new BufferedReader(new FileReader(filename))){
93
+ String[] rowcol = br.readLine().split(" ");
94
+ row = Integer.parseInt(rowcol[0]);
95
+ col = Integer.parseInt(rowcol[1]);
96
+ matrix = new double[row][col];
97
+ for (int m = 0; m < row; m++) {
98
+ String[] record = br.readLine().split(" ");
99
+ for (int n = 0; n < col; n++)
100
+ matrix[m][n] = Double.parseDouble(record[n]);
101
+ }
102
+ }
103
+ catch (FileNotFoundException e) {
104
+ e.printStackTrace();
105
+ }
106
+ catch (IOException e) {
107
+ e.printStackTrace();
108
+ }
109
+ catch (NumberFormatException e) {
110
+ e.printStackTrace();
111
+ }
112
+ }
113
+
114
+ public void print() {
115
+ for (int i = 0; i < row; i++) {
116
+ for (int j = 0; j < col; j++)
117
+ System.out.print(" " + matrix[i][j]);
118
+ System.out.println();
119
+ }
120
+ System.out.println();
121
+ }
122
+
123
+ public Matrix multiply(Matrix b) {
124
+ if (col != b.row) return null;
125
+ Matrix c = new Matrix(row, b.col);
126
+ for (int i = 0; i < row; i++)
127
+ for (int j = 0; j < col; j++) {
128
+ c.matrix[i][j] = 0;
129
+ for (int k = 0; k < b.row; k++)
130
+ c.matrix[i][j] += matrix[i][k] * b.matrix[k][j];
131
+ }
132
+ return c;
133
+ }
134
+
135
+ public static void main(String[] args){
136
+ if (args.length != 2) {
137
+ System.out.println("need two files");
138
+ System.exit(1);
139
+ }
140
+
141
+ Matrix a = new Matrix();
142
+ a.read(args[0]);
143
+ a.print();
144
+
145
+ Matrix b = new Matrix();
146
+ b.read(args[1]);
147
+ b.print();
148
+
149
+ Matrix c = a.multiply(b);
150
+ c.print();
151
+ }
152
+ }
72
153
  ```