从大矩阵

时间:2017-11-22 09:33:43

标签: java matrix block

启动大小为 nxn 的矩阵 M 。将M划分为大小为 bxb 的subMatrix。例如,如果 n = 16 b = 8 ,那么我的 4 subMatrix的大小 8x8 。这是该功能的实现工作正常。

 public static int[][] getAcutalBlock(int[][] mat, int row, int col, int number) {

    /* mat is orignal big matrix of size nxn
     row is starting index for the block i
     col is staring index for the block *
     number is representing block ID either first block, second block or ... 
    */

    int[][] block = new int[blockSize][blockSize];
    int eRow = row + blockSize;
    int eCol = col + blockSize;

    if (number == 0) {   // it is for first block
        for (int i = row; i < eRow; i++) {
            for (int j = col; j < eCol; j++) {
                block[i][j] = mat[i][j];
            }
        }
    }
    else if(number == totalBlocks-1){ // it is for last block
        for (int i = row; i < eRow; i++) {
            for (int j = col; j < eCol; j++) {
                block[i - blockSize][j - blockSize] = mat[i][j];
            }
        }
    }
    else if (isEven(number)) { // if the number is even
        for (int i = row; i < eRow; i++) {
            for (int j = col; j < eCol; j++) {
                block[i - blockSize][j] = mat[i][j];
            }
        }
    }
    else { // if the number is odd
        for (int i = row; i < eRow; i++) {
            for (int j = col; j < eCol; j++) {
                block[i][j - blockSize] = mat[i][j];
            }
        }
    }
    return block;
}

但问题是它不是动态的。如果更改了 b ,那么除了第一个最后一个块之外,如何读取中间块?我想让它对任意数量的 n 和任意数量的 b 都是通用的。 任何教程或代码示例将不胜感激。感谢。

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解这个问题,但我会试一试。

如果我理解正确,则数字表示您要访问的子矩阵和 col - - 变量是相应的位置那个矩阵。因此,四个子矩阵的表示将类似于

0 | 1
------
2 | 3

9x9矩阵看起来像

0 | 1 | 2
----------
3 | 4 | 5
----------
6 | 7 | 8

如果是这种情况,那么我只会像你已经为 number == 0 那样做了一个双嵌套for循环,但是添加了 mat -matrix通过包含矩阵的起始索引和循环中的当前索引的计算来检索所需元素。代码可能看起来像这样

int[][] block = new int[blockSize][blockSize];

// to get how many matrices that are put next to each other on a row
int numbersOfSubMatricesPerSide = mat.length / blockSize; 

// starting position for this matrix column wise
int colStart = (number % numbersOfSubMatricesPerSide) * blockSize; 

// starting position for this matrix row wise
int rowStart = (number / numbersOfSubMatricesPerSide) * blockSize; 

// fill the sub-matrix
for (int i = 0; i < blockSize; i++) {
    for (int j = 0; j < blockSize; j++) {
        block[i][j] = mat[colStart + i][rowStart + j];
    }
}

return block;

所以说如果我们有 b = 10 n = 30 并且我们想要创建矩阵#1(中间顶部)那么我们得到 colStart = blockSize rowStart = 0 意味着对于我们的块,我们从mat-matrix收集数据,起始于(blockSize,0)并以(2 * blockSize - 1结尾) ,blockSize - 1)
=&GT;从(10,0)开始到(19,9)结束。

希望这有帮助!