I have got a matrix say A of size M X N. I have to call same function for each column throughout the matrix. Till now, I have been extracting each column and calling the function over the column iterating till N. i.e. (No. of Columns)
Is there any better/faster way to do it?
Any help appreciated. Thanks
Nowadays if you can you can boost performance using parallel computing.
The CPU are multicore/multithread.
You can use for example java 8 stream and parallel computation.
for example
@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 }