2

我有一个大小为 MX N 的矩阵A。必须为整个矩阵的每一列调用相同的函数。到目前为止,我一直在提取每一列并在列上调用函数,迭代直到 N。即(列数)

有没有更好/更快的方法来做到这一点?

任何帮助表示赞赏。谢谢

4

1 回答 1

1

如今,如果可以的话,您可以使用并行计算来提高性能。

CPU是多核/多线程。

您可以使用例如 java 8 流和并行计算。

例如

矩阵向量乘法

@Test 
  2 public static void matrixVectorProduct() {
  3     System.out.println("Matrix Vector multiplication"); 
  4     final int DIM = 5;
  5          
  6     int [][]a = new int[DIM][DIM]; 
  7     int counter = 1;
  8     for (int i = 0; i < a.length; i++) {
  9         for (int j = 0; j < a[0].length; j++) {
 10             a[i][j] = counter++; 
 11         } 
 12     } 
 13          
 14     int []v = new int[DIM]; 
 15     Arrays.fill(v, 5);        
 16     int []c = new int[DIM]; 
 17          
 18     IntStream.range(0, c.length) 
 19              .parallel() 
 20              .forEach( (i) ->  { 
 21                  IntStream.range(0, a.length)
 22                           .sequential() 
 23                           .forEach( (j) -> { c[i] += v[j] * a[i][j]; }); 
 24                          }); 
 25   
 26          
 27     int []expected = new int[]{75, 200, 325, 450, 575};
 28     assertArrayEquals(expected, c); 
 29          
 30     System.out.println("Matrix-Vector product: " + Arrays.toString(c));         
 31 }
于 2015-06-28T19:40:30.633 回答