Riccardo Rigon
Riccardo Rigon

Reputation: 61

Matrix multiplication java 1.8

Do you think it would be possible to implement sparse matrix operations using the new Stream interface in Java 1.8 ? If yes, how do we need to implement the matrixes and the operations. Clearly, I am looking for it for being able eventually to use the "automatic" parallelization.

Upvotes: 4

Views: 1053

Answers (1)

paul-g
paul-g

Reputation: 3877

It can clearly be done. How about something like below for a simple SPMV (Sparse matrix vector multiplication), with the sparse matrix represented in the coordinate COO format (the simplest sparse format out there):

class COO {
    int x, y, value;
}

public static ArrayList<Integer> spmv(List<COO> values, ArrayList<Integer> v) {
    final ArrayList<Integer> result = new ArrayList<>(Collections.nCopies(v.size(), 0));
    values.stream().forEach(
            coo -> result.set(coo.x, result.get(coo.x) + coo.value * v.get(coo.y))
    );
    return result;
}

But I sincerely suggest you use something pre-coded, if you don't want to spend the next 3 years of your life understanding the performance implications of sparse matrix operations. This is quite a large research/optimisation topic and there are many factors to consider like (just off the top of my head):

  1. scheduling / reordering of matrix values to improve cache performance
  2. using an optimal storage format for specific problems (e.g. see this survey on netlib)

There are many implementations out there that can achieve orders of magnitude improvements in performance versus hand crafted implementation. To name a few, check out:

  1. Intel MKL Sparse BLAS

  2. Nvidia's cuBLAS

I would just write bindings to those if they don't exist already, although something like la4j looks quite promising.

Upvotes: 2

Related Questions