在java中引用子矩阵 [英] Getting reference of a sub-matrix in java

查看:177
本文介绍了在java中引用子矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要递归地进行子矩阵的并行处理(原始矩阵分为4个传递给一个方法)。矩阵被存储为2D数组。我不能每次将元素复制到一个新的矩阵,因为它是非常昂贵的。有没有可以参考java中的子矩阵?

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.

推荐答案

我将在 int [] [] 数据周围编写一个包装器,并将其称为Matrix类。然后写一个方法 getSubMatrix(x,y,rows,cols)。这是一个简单的Matrix类:

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("\n");
        }
        sb.setLength(sb.length() - 1);

        return sb.toString();
    }
}

此测试程序...:

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));

}

...打印:

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 

这篇关于在java中引用子矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆