티스토리 뷰

Dev/Java

[Java] 자바 행렬 연산 (Matrix Operation)

꿈을 위해 잠을 잊은 그대에게 2020. 3. 10. 17:39

Matrix.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
 
public class Matrix {
    public static final int NOT_FOUND = -2147483646;
    private double[][] matrix;
    private int row;    // 행
    private int col;    // 열
    // 행과 열의 크기가 같은 생성자
    public Matrix(int equal) {
        this.row = equal;
        this.col = equal;
        matrix = new double[equal][equal];
        for (int i = 0; i < equal; i++) {
            for (int j = 0; j < equal; j++) {
                matrix[i][j] = (int) (Math.random() * 10 * Math.pow(-1, (intMath.random() * 10));
            }
        }
    }
    // 행과 열의 크기가 다른 생성자
    public Matrix(int row, int col) {
        this.row = row;
        this.col = col;
        matrix = new double[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                matrix[i][j] = (int) (Math.random() * 10 * Math.pow(-1, (intMath.random() * 10));
            }
        }
    }
    // 임의의 행렬을 입력받는 생성자
    public Matrix(double[][] temp) {
        this.matrix = temp;
        row = temp.length;
        col = temp[0].length;
    }
    /*
     * @param temp 
     * 행렬의 값을 temp로 바꿈
     */
    public void setMatrix(double temp[][]) {
        // 행렬 내용 수정 temp와 matrix가 다를 시 문제가 생길 수 있음
        // length로 행과 열의 길이를 파악
        this.row = temp.length;
        this.col = temp[0].length;
        this.matrix = temp;
    }
    // 자기 자신을 영행렬로 바꾼다.
    public void setZeroMatrix() {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                matrix[i][j] = 0;
            }
        }
    }
    // 자기 자신을 모두 1인 행렬로 바꾼다.
    public void setOnesMatrix() {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                matrix[i][j] = 1;
            }
        }
    }
    // 자기 자신을 단위행렬로 바꾼다.
    public void setUnitMatrix() {
        setZeroMatrix();
        for (int i = 0; i < row; i++) {
            matrix[i][i] = 1;
        }
    }
    // @return Matrix의 배열을 리턴
    public double[][] getMatrix() {
        return matrix;
    }
    // @return 행의 크기
    public int getRowSize() {
        return this.row;
    }
    // @return 열의 크기
    public int getColSize() {
        return this.col;
    }
    /*
     * 0행렬 만들기
     * @param row 행 크기
     * @param col 열 크기
     * @return
     */
    public static Matrix zeros(int row, int col) {
        Matrix temp = new Matrix(row, col);
        temp.setZeroMatrix();
        return temp;
    }
    /*
     *  i * i 크기의 0행렬
     *  @param i
     *  @return
     */
    public static Matrix zeros(int i) {
        return Matrix.zeros(i, i);
    }
    /*
     * 1행렬 만들기
     * @param row 행 크기
     * @param col 열 크기
     * @return
     */
    public static Matrix ones(int row, int col) {
        Matrix temp = new Matrix(row, col);
        temp.setOnesMatrix();
        return temp;
    }
    /*
     * i * i 크기의 1행렬
     * @param i
     * @return
     */
    public static Matrix ones(int i) {
        return Matrix.ones(i, i);
    }
    /*
     * i * i의 단위행렬
     * @param i
     * @return
     */
    public static Matrix unitMatrix(int i) {
        Matrix temp = new Matrix(i);
        temp.setUnitMatrix();
        return temp;
    }
    /*
     * 행렬의 모양 비교
     * @param A
     * @param B
     * @return
     */
    public static boolean equalSize(Matrix A, Matrix B) {
        if (A.getRowSize() == B.getRowSize() && A.getColSize() == B.getColSize()) {
            return true;
        } else {
            return false;
        }
    }
    /*
     * @param m 비교할 행렬
     * @return 현재 행렬과 m이 같으면 true
     */
    public boolean equals(Matrix m) {
        if (m.row == this.row && m.col == this.col) {
            for (int i = 1; i < row; i++) {
                for (int j = 1; j < col; j++) {
                    if (Math.abs(m.matrix[i][j] - this.matrix[i][j]) >= 0.0000001) {
                        // 컴퓨터로 계산한 값이기 때문에 두 값의 차가 0.0000001보다 작으면 같다고 볼 수 있다. 행렬의 원소 자체가 매우 작으면 문제가 발생할 수 있으나 이 경우는 무시하기로 한다.
                        return false;
                    }
                }
            }
        }
        return true;
    }
    /*
     * @return 행렬의 원소 중 Not a Number인 원소가 있다면 true
     */
    public boolean isNan() {
        for (int i = 0; i < col; i++) {
            for (int j = 0; j < row; j++) {
                if (Double.isNaN(matrix[j][i])) {
                    return false;
                }
            }
        }
        return true;
    }
    /*
     * 행렬의 합
     * @param A
     * @param B
     * @return
     */
    public static Matrix plus(Matrix A, Matrix B) {
        double[][] temp = Matrix.zeros(A.row, A.col).getMatrix();
        double[][] tempA = A.getMatrix();
        double[][] tempB = B.getMatrix();
        if (equalSize(A, B)) {
            for (int i = 0; i < tempA.length; i++) {
                for (int j = 0; j < tempA[0].length; j++) {
                    temp[i][j] = tempA[i][j] + tempB[i][j];
                }
            }
            return new Matrix(temp);
        }
        return new Matrix(temp);
    }
    /*
     * 행렬의 차
     * 
     * @param A
     * @param B
     * @return
     */
    public static Matrix minus(Matrix A, Matrix B) {
        double[][] temp = Matrix.zeros(A.row, A.col).getMatrix();
        double[][] tempA = A.getMatrix();
        double[][] tempB = B.getMatrix();
        if (equalSize(A, B)) {
            for (int i = 0; i < tempA.length; i++) {
                for (int j = 0; j < tempA[0].length; j++) {
                    temp[i][j] = tempA[i][j] - tempB[i][j];
                }
            }
            return new Matrix(temp);
        }
        return new Matrix(temp);
    }
    /*
     * 가우스 소거법에 의한 행렬식 계산
     * @param target
     * @return
     */
    public static double determinant(Matrix target) {
        if (target.getRowSize() == target.getColSize()) {
            double[][] temp = new double[target.row][target.row];
            // temp=getMatrix()로 하면 레퍼런스가 되어서 본래 행렬이 변경됨
            for (int i = 0; i < target.row; i++) {
                for (int j = 0; j < target.row; j++) {
                    temp[i][j] = target.matrix[i][j];
                }
            }
            for (int n = 0; n < temp.length; n++) {
                if (temp[n][n] == 0) {
                    for (int a = n; a < temp.length; a++) {
                        if (temp[a][n] != 0) {
                            for (int b = n; b < temp.length; b++) {
                                temp[n][b] += temp[a][b];
                            }
                            break;
                        }
                    }
                    if (temp[n][n] == 0) {
                        System.out.println(n + "ss");
                        return 0;
                    }
                }
                for (int i = n + 1; i < temp.length; i++) {
                    for (int j = temp[0].length - 1; j >= n; j--) {
                        temp[i][j] = temp[i][j] - temp[i][n] * temp[n][j] / temp[n][n];
                    }
                }
            }
            double sum = 1;
            for (int i = 0; i < temp.length; i++) {
                sum *= temp[i][i];
            }
            return sum;
        } else {
            System.out.println("행렬식을 구할 수 없습니다.");
            return NOT_FOUND;
        }
    }
    /*
     * 행렬식을 계산한다.
     * determinant()를 사용
     * 
     * @param target
     * @return target의 행렬식
     */
    public static double determinant1(Matrix target) {
        // 라이프니츠 공식에 의한 행렬식 계산
        double det = 0;
        if (target.getRowSize() == target.getColSize()) {
            double[][] A = target.getMatrix();
            if (A.length == 1) {
                return A[0][0];
            } else {
                for (int i = 0; i < A[0].length; i++) {
                    det += A[0][i] * target.cofactor(0, i);    // 재귀
                }
            }
            return det;
        }
        System.out.println("행렬식을 구할 수 없습니다.");
        return NOT_FOUND;
    }
    // 행렬식
    public double determinant() {
        return Matrix.determinant(this);
    }
    @Override
    public String toString() {
        String temp = "";
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (matrix[i][j] == -0) {
                    matrix[i][j] = 0;
                }
                temp += Double.toString(matrix[i][j]);
                if (j != col - 1) {
                    temp += ",  ";
                }
            }
            temp += System.getProperty("line.separator");
        }
        return temp;
    }
    /*
     * 소행렬 구하기
     * @object target
     * @param removeRow
     * @param removeCol
     * @return target의 row 행과 col 열을 제외한 소행렬
     */
    public Matrix minor(int removeRow, int removeCol) {
        int ar = 0;
        int ac = 0;
        double temp[][] = new double[row - 1][col - 1];
        for (int r = 0; r < row; r++) {
            for (int c = 0; c < col; c++) {
                if (!(r == removeRow || c == removeCol)) {
                    temp[ar][ac] = matrix[r][c];
                    if (++ac >= col - 1) {
                        if (++ar < row - 1) {
                            ac = 0;
                        }
                    }
                }
            }
        }
        return new Matrix(temp);
    }
    /*
     * 여인수
     * @param row
     * @param col
     * @return
     */
    public double cofactor(int row, int col) {
        return minor(row, col).determinant() * Math.pow((-1), row + col);
    }
    /*
     * 전치행렬
     * @return 이 행렬의 전치행렬
     */
    public Matrix transpose() {
        Matrix tempM = new Matrix(col, row);
        double temp[][] = new double[col][row];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                temp[j][i] = matrix[i][j];
            }
        }
        tempM.setMatrix(temp);
        return tempM;
    }
    /*
     * 행렬의 상수배
     * @param m 행렬에 곱할 수
     * @return 현재 행렬의 m배가 된 행렬
     */
    public Matrix multiply(double m) {
        Matrix temp = new Matrix(row, col);
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                temp.matrix[i][j] = this.matrix[i][j] * m;
            }
        }
        return temp;
    }
    /*
     * 행렬의 곱
     * @param postMatrix 현재 행렬에 곱해질 행렬
     * @return 현재 행렬 X postMatrix
     */
    public Matrix multiply(Matrix postMatrix) {
        // Matrix temp;
        double[][] temp;
        // 곱하기 위해 앞쪽 행렬의 열과 뒷쪽 행렬의 행이 같아야 함
        if (this.col == postMatrix.row) {
            temp = Matrix.zeros(this.row, postMatrix.col).getMatrix();
            double[][] A = this.getMatrix();
            double[][] B = postMatrix.getMatrix();
            for (int i = 0; i < this.row; i++) {
                for (int j = 0; j < postMatrix.col; j++) {
                    for (int k = 0; k < this.col; k++) {
                        temp[i][j] += A[i][k] * B[k][j];
                    }
                }
            }
            return new Matrix(temp);
        } else {
            System.out.println("계산할 수 없습니다.");
            return Matrix.zeros(1);
        }
    }
    /*
     * 역행렬
     * invers()를 사용
     * 
     * @return 현재 행렬의 역행렬
     */
    public Matrix inverse1() {
        // 역행렬
        // 행렬의 크기가 8x8이 넘어가면 출력 시 시간이 너무 오래 걸린다.
        // 알고리즘의 최적화가 필요. => inverse() 알고리즘 변경
        Matrix temp = null;
        if (row == col) {    // 행==열 인 행렬인지 확인
            temp = Matrix.zeros(row);
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < row; j++) {
                    temp.matrix[i][j] = cofactor(i, j);    // i행 j열의 값 = 여인수(i, j)
                }
            }
            temp = temp.transpose();    // 전치
            double det = determinant1(this);
            // 원래 행렬의 행렬식 계산
            if (det != 0) {
                // 마지막으로 행렬식으로 나눠준다.
                return temp.multiply(1.0 / det);
            } else {
                System.out.println("역행렬이 없습니다.");
                // 행렬식==0이면 역행렬이 없다.
                return Matrix.zeros(1);
            }
        } else {
            System.out.println("행과 열의 크기가 같지 않습니다.");
            return Matrix.zeros(1);
        }
    }
    /*
     * 역행렬
     * 
     * 가우스 조던 소거법
     * inverse1에 비하여 매우 빠르다. inverse는 9차 이상의 행렬에서 동작속도를 보장할 수 없다.
     * 하지만 이것은 100차 행렬이 넘어가도 빠른속도로 계산이 가능하다.
     * 그러나 역행렬이 존재하지 않는 행렬에서도 답이 나오므로 선행해서 걸러낼 필요가 있다.
     * 마지막에 원래 행렬과 만들어진 역행렬을 곱해서 단위행렬이 나오는지 검사한다.
     * 
     * @return 현재 행렬의 역행렬. 역행렬을 만들 수 없는 경우에는 null
     */
    public Matrix inverse() {
        double[][] temp = new double[row][row];
        // temp = this.getMatrix()로 하면 레퍼런스가 되어서 본래행렬이 변경됨
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < row; j++) {
                temp[i][j] = matrix[i][j];
            }
        }
        double[][] comp = Matrix.unitMatrix(col).getMatrix();
        for (int n = 0; n < col; n++) {
            if (temp[n][n] == 0) {
                for (int k = n; k < col; k++) {
                    if (temp[k][n] != 0) {
                        for (int a = 0; a < col; a++) {
                            comp[n][a] = comp[n][a] + comp[k][a];
                            temp[n][a] = temp[n][a] + temp[k][a];
                        }
                        break;
                    }
                }
            }
            double p = temp[n][n];
            for (int a = 0; a < col; a++) {
                comp[n][a] /= p;
                temp[n][a] /= p;
            }
            for (int i = 0; i < col; i++) {
                if (i != n) {
                    double p1 = temp[i][n];
                    for (int j = col - 1; j >= 0; j++) {
                        comp[i][j] -= p1 * comp[n][j];
                        temp[i][j] -= p1 * temp[n][j];
                    }
                }
            }
        }
        Matrix tempReturn = new Matrix(comp);
        if (multiply(tempReturn).equals(Matrix.unitMatrix(row))) {    // 만들어진 결과가 역행렬이 맞는지 확인
            return tempReturn;
        } else {
            System.out.println("경고! 역행렬이 존재하지 않는 행렬일 수 있습니다.");
            return null;
        }
    }
    /*
     * 왼쪽 나눗셈
     * 
     * 선형방정식의 해를 구할 때 쓴다.
     * this*X=temp, X=this*temp 일 때 X를 구할 수 있다.
     * 
     * @param temp
     * @return
     */
    public Matrix leftDivision(Matrix temp) {
        return this.inverse().multiply(temp);
    }
    /*
     * 수반행렬
     * 
     * @return
     */
    public Matrix adjoint() {
        double temp[][] = new double[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                temp[i][j] = cofactor(i, j);
            }
        }
        return new Matrix(temp);
    }
    /*
     * 행렬의 덧셈
     * 
     * @param A 더해질 행렬
     * @return 현재 행렬에 A를 더한 행렬
     */
    public Matrix plus(Matrix A) {
        double[][] temp = Matrix.zeros(A.row, A.col).getMatrix();
        if (equalSize(A, this)) {
            for (int i = 0; i < A.getRowSize(); i++) {
                for (int j = 0; j < A.getColSize(); j++) {
                    temp[i][j] = A.matrix[i][j] + this.matrix[i][j];
                }
            }
            return new Matrix(temp);
        }
        return new Matrix(temp);
    }
    /*
     * 행렬의 뺄셈
     * 
     * @param A 더해질 뺄셈
     * @return 현재 행렬에 A를 뺀 행렬
     */
    public Matrix minus(Matrix A) {
        // 행렬 뺄셈
        double[][] temp = Matrix.zeros(A.row, A.col).getMatrix();
        if (equalSize(A, this)) {
            for (int i = 0; i < A.getRowSize(); i++) {
                for (int j = 0; j < A.getColSize(); j++) {
                    temp[i][j] = A.matrix[i][j] - this.matrix[i][j];
                }
            }
            return new Matrix(temp);
        }
        return new Matrix(temp);
    }
    // 행렬 출력
    public void displayMatrix() {
        System.out.println(this);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

OperationTest.java

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 
public class OperationTest {
    public static void main(String[] args) {
        // 임의의 행렬 선언
        double[][] arr1 = {{1,2,3,4},{4,5,6,7},{3,2,1,9},{4,2,8,9}};
        double[][] arr2 = {{3,4,5,2},{6,5,4,7},{1,2,3,5},{3,2,7,1}};
 
        Matrix m1 = new Matrix(arr1);
        Matrix m2 = new Matrix(arr2);
//        // 행렬의 덧셈
//        m2 = m2.plus(m1);
//        m2.displayMatrix();
        
//        // 행렬의 뺄셈
//        m2 = m2.minus(m1);
//        m2.displayMatrix();
        
//        // 행렬의 곱
//        m2 = m2.multiply(m1);
//        m2.displayMatrix();
        
//        // 수반행렬
//        m2 = m2.adjoint();
//        m2.displayMatrix();
    
//        // 전치행렬
//        m2 = m2.transpose();
//        m2.displayMatrix();
        
//        // 행렬의 합
//        m2 = Matrix.plus(m2, m1);
//        m2.displayMatrix();
        
//        // 행렬의 차
//        m2 = Matrix.minus(m2, m1);
//        m2.displayMatrix();
        
//        // 역행렬
//        m2 = m2.inverse1();
//        m2.displayMatrix();
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크