Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to do parallel processing of sub-matrices recursively (original matrix divided into 4 passed into a method). The matrix is stored as a 2D array. I can't copy the elements each time to a new matrix as it turns out to be very expensive. Is there someway to reference the sub-matrices in java?

Perhaps, the question was not clear, I didn't get an answer here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
781 views
Welcome To Ask or Share your Answers For Others

1 Answer

I would write a wrapper around the int[][] data and call it a Matrix class. Then write a method getSubMatrix(x, y, rows, cols). This is a simple Matrix class:

static class Matrix {
    int[][] data;
    int x, y, columns, rows;

    public Matrix(int[][] data) {
        this(data, 0, 0, data.length, data[0].length);
    }

    private Matrix(int[][] data, int x, int y, int columns, int rows) {
        this.data = data;
        this.x = x;
        this.y = y;
        this.columns = columns;
        this.rows = rows;
    }

    public Matrix getSubMatrix(int x, int y, int columns, int rows) {
        return new Matrix(data, this.x + x , this.y + y, columns, rows);
    }

    public String toString() {

        StringBuffer sb = new StringBuffer();

        for (int i = y; i < x + rows; i++) {
            for (int j = x; j < x + columns; j++)
                sb.append(data[i][j]).append(" ");

            sb.append("
");
        }
        sb.setLength(sb.length() - 1);

        return sb.toString();
    }
}

This test program...:

public static void main(String[] args) throws IOException {

    int[][] testData = new int[10][10];

    for (int i = 0; i < testData.length; i++) 
        for (int j = 0; j < testData[i].length; j++)
            testData[i][j] = 100 + i + j;

    Matrix full = new Matrix(testData);

    System.out.println("Full test matrix:");
    System.out.println(full);

    System.out.println();

    System.out.println("Part of the matrix:");
    System.out.println(full.getSubMatrix(3, 3, 3, 3));

}

...prints:

Full test matrix:
100 101 102 103 104 105 106 107 108 109 
101 102 103 104 105 106 107 108 109 110 
102 103 104 105 106 107 108 109 110 111 
103 104 105 106 107 108 109 110 111 112 
104 105 106 107 108 109 110 111 112 113 
105 106 107 108 109 110 111 112 113 114 
106 107 108 109 110 111 112 113 114 115 
107 108 109 110 111 112 113 114 115 116 
108 109 110 111 112 113 114 115 116 117 
109 110 111 112 113 114 115 116 117 118 

Part of the matrix:
106 107 108 
107 108 109 
108 109 110 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...