I am a new to Java. I want to create a 2d java arrays based on compressed sparse column matrix parameters. For example, I can create an 2d arrays by using the following code in python:
from scipy.sparse import csc_matrix
indices = [0, 2, 2, 0, 1, 2]
indptr = [0,2,3,6]
data = [1, 2, 3, 4, 5, 6]
shape = [3,3]
sp_mat = csc_matrix((data, indices, indptr), shape=shape).todense()
print(sp_mat)
[[1 0 4]
[0 0 5]
[2 3 6]]
But I don't know how to achieve it in Java.
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
int[] indices = new int[]{0, 2, 2, 0, 1, 2};
int[] indptr = new int[]{0, 2, 3, 6};
int[] data = new int[]{1, 2, 3, 4, 5, 6};
int[] shape = new int[]{3, 3};
// some code to create 2D arrays
}
}
I will have indices
, indptr
, data
and shape
1d array as above code. I expect to be able to create the following 2d arrays:
int[][] sp_mat = new int[][]{{1, 0, 4}, {0, 0, 5}, {2, 3, 6}};
I finally found what I needed Java la4j library. First add dependencies:
<dependency>
<groupId>org.la4j</groupId>
<artifactId>la4j</artifactId>
<version>0.6.0</version>
</dependency>
Then I can create CCSMatrix
martix and convert matrix to 2d arrays.
import java.io.IOException;
import org.la4j.matrix.sparse.CCSMatrix;
public class Main {
public static void main(String[] args) throws IOException {
int[] indices = new int[]{0, 2, 2, 0, 1, 2};
int[] indptr = new int[]{0, 2, 3, 6};
double[] data = new int[]{1, 2, 3, 4, 5, 6};
int[] shape = new int[]{3, 3};
// some code to create 2D arrays
CCSMatrix a = new CCSMatrix(
shape[0], shape[1], data.length, data, indices, indptr);
double[][] mat = a.toDenseMatrix().toArray();
}
}