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
| import edu.princeton.cs.algs4.*; public class q1133{
public static double dot(double[] x, double[] y) { if(x.length != y.length) System.exit(1); double res = 0.0; for(int i = 0; i < x.length; i++){ res += x[i] * y[i]; } return res; }
public static double[][] multiple(double[][] a, double[][] b) { if(a[0].length != b.length) System.exit(1); double[][] matrix = new double[a.length][b[0].length]; for (int i = 0; i < a.length; i++){ for (int j = 0; j < b[0].length; j++){ for (int k = 0; k < b.length; ++k){ matrix[i][j] += a[i][k] * b[k][j]; } } } return matrix; }
public static double[] multiple(double[][] a, double[] x) { if(a[0].length != x.length) System.exit(1); double[] matrix = new double[x.length]; for(int i = 0; i < a.length; i++){ for(int j = 0; j < x.length; j++){ matrix[i] += a[i][j] * x[j]; } } return matrix; }
public static double[] multiple(double[] y, double[][] a) { double[] matrix = new double[y.length]; for(int i = 0; i < y.length; i++){ for(int j = 0; j < a[i].length; j++){ matrix[i] += y[j] * a[j][i]; } } return matrix; }
public static double[][] transpose(double[][] a) { for(int i = 0; i < a.length; i++){ for(int j = 0; j < i; j++) { double temp = a[i][j]; a[i][j] = a[j][i]; a[j][i] = temp; } } return a; }
public static void main(String[] args) { StdOut.println("-------- 向量点乘 ---------"); double[] a0 = {1, 2, 3}; double[] b0 = {4, 5, 6}; double res0 = dot(a0, b0); StdOut.println(res0);
StdOut.println("-------- 矩阵乘法 ---------"); double[][] a1 = { {1, 2}, {3, 4}, {5, 6} }; double[][] b1 = { {1, 2, 3}, {4, 5, 6} }; double[][] res1 = multiple(a1, b1); for(int i = 0; i < res1.length; i++) { for (int j = 0; j < res1[i].length; j++){ StdOut.printf("%-10.3f", res1[i][j]); } StdOut.println(); }
StdOut.println("-------- 矩阵转置 ---------"); double[][] a2 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; double[][] c2 = transpose(a2); for(int i = 0; i < a2.length; i++) { for (int j = 0; j < a2[i].length; j++){ StdOut.printf("%-10.3f", a2[i][j]); } StdOut.println(); }
StdOut.println("----- 矩阵和向量之积 ------"); double[][] a3 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; double[] b3 = {1, 2, 3}; double[] c3 = multiple(a3, b3); for(int i = 0; i < c3.length; i++){ StdOut.printf("%-10.3f\n", c3[i]); }
StdOut.println("----- 向量和矩阵之积 ------"); double[] a4 = {1, 2, 3}; double[][] b4 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; double[] c4 = multiple(a4, b4); for(int i = 0; i < c4.length; i++){ StdOut.printf("%-10.3f", c4[i]); } } }
|