euraad
euraad

Reputation: 2836

What is the fastest way to get double[][] to a MATLAB matrix in Java?

I need to use MATLAB/Octave with ProcessBuilder class in Java. I have one argument and it going to be a very very long string that are shaped as a MATLAB/Octave array.

[1 2 3 4;
 4 5 6 3; 
 .
 .
 .
 3 4 2 5]

So I begun to code where A is the matrix and matA is going to be the argument in ProcessBuilder object.

    String matA = "[";
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < columns; j++) {
            matA = matA + " " + A[i][j];
        }
        if(i < rows-1)
            matA = matA + ";";
    }
    matA = matA + "]";
    System.out.println(matA);

Like this:

        ProcessBuilder processBuilder = new ProcessBuilder(matA);
        processBuilder.command("singularvaluesdecomposition.m");
        try {
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

And my MATLAB/Octave file looks like this:

function singularvaluesdecomposition(A)
    [U, S, ~] = svd(A);
    U
    diag(S)
end

But building matA takes enormus amout of time. Is there any faster whay todo this?

Upvotes: 2

Views: 66

Answers (1)

Majid Roustaei
Majid Roustaei

Reputation: 1764

when changing data a lot, it is better to use StringBuilder instead of String. Strings are immutable and changing them is done by making another object, though the user can't see that visually.

try this:

StringBuilder matA = new StringBuilder("[");
for(int i = 0; i < rows; i++) {
    for(int j = 0; j < columns; j++) {
        matA.append(" " + A[i][j]);
    }
    if(i < rows-1)
        matA.append(";");
}
matA.append("]");
System.out.println(matA);

for more info: https://javapapers.com/java/java-string-vs-stringbuilder-vs-stringbuffer-concatenation-performance-micro-benchmark/

Upvotes: 2

Related Questions