Question

Let's say I have a NxN matrix full of random integers in the range of one to ten. Now, I want to call PROC(A(1:n/2, 1:n/2)+A(n/2+1:n, n/2+1:n)... where n is the size of the matrix. In other words, I want to make a submatrix starting at the first row and column of A and going until half the size of A and then add that to a submatrix that starts at half the size of A plus one and goes until the end of A.

The partition function that I am using is this:

public Matrix partition(int rowStart, int rowEnd, int colStart, int colEnd) {
    // int r = 0;
    // int c = 0;
    if (this.N%2 != 0) throw new RuntimeException("Illegal matrix dimensions.");
    Matrix C = new Matrix((this.N)/2);
    for (int i=rowStart-1; i<rowEnd; i++) {
        for (int j=colStart-1; j<colEnd; j++) {
            C.data[i][j] = this.data[i][j];
            // C.data[r][c] = this.data[i][j];
            c++;
        }
        r++;
    }
    return C;
}

Now, this works for finding the submatrix at the top left (Matrix C = m.partition(1, m.size()/2, 1, m.size()/2);) of a given matrix.

 9.00     5.00     0.00     3.00
 0.00     7.00     8.00     3.00
 9.00     3.00    10.00     8.00
 0.00     6.00     2.00     0.00

 9.00     5.00
 0.00     7.00

But when I try to get another submatrix (Matrix D = m.partition(m.size()/2+1, m.size(), m.size()/2+1, m.size());) I get an ArrayIndexOutOfBoundsException: 2. I've tried adding separate row and column counters to my partition function, but it gave the same error. How can I modify my partition function to work with all input and still give the correct output?

Was it helpful?

Solution

C.data[i][j] = this.data[i][j];<-- Culprit

i is rowStart-1 and j is rowEnd-1 you need i and j to start from 0 for C.data

for (int i=rowStart-1,p=0; i<rowEnd; i++,p++) {
        for (int j=colStart-1,q=0; j<colEnd; j++,q++) {
            C.data[p][q] = this.data[i][j];
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top