javatoeplitz

Toeplitz matrix initialization


I am trying to initialize a Toeplitz matrix in java. I want it to have this form
6 -4 1 0 0 ... 0 -4 6 -4 1 0 ... 0 1 -4 6 -4 1 ...0 ................ 0 ... 1 -4 6 -4 1 0 ... ...1 -4 6-4 0 .. ... 0 1 -4 6

I realized that the problem is in the if(j>i) in the bounds of data[i-j-1] . I tried to change it but i get the IndexOutOfBounds error. Here is the code i've written so far

    int a1[][] = new int[size][size];


    int data[] = new int[size];

    data[0] = 6;
    data[1] = -4;
    data[2] = 1;

    for(int i=3; i<size; i++){
        data[i] = 0;
    }

    /* Creating the A1 matrix */
    for(int i=0; i<size; i++)
    {
        for(int j=0; j<size; j++)
        {
            if(j>i){
                a1[i][j] = data[j-i-1];

            }else if(j==i){
                a1[i][j] = data[0];

            }else{
                a1[i][j] = data[i-j-1];
            }


        }
    }

And the output is

    The Matrix is : 
6   6   -4  1   0   0   0   0   0   0   
6   6   6   -4  1   0   0   0   0   0   
-4  6   6   6   -4  1   0   0   0   0   
1   -4  6   6   6   -4  1   0   0   0   
0   1   -4  6   6   6   -4  1   0   0   
0   0   1   -4  6   6   6   -4  1   0   
0   0   0   1   -4  6   6   6   -4  1   
0   0   0   0   1   -4  6   6   6   -4  
0   0   0   0   0   1   -4  6   6   6   
0   0   0   0   0   0   1   -4  6   6   

Solution

  • The problem is if i = j+1 or j = i+1, a1 is assigned a1[i][j] = data[0]. This is an off-by-one mistake, you should remove the 1:

    for(int j=0; j<size; j++) {
        if(j>i){
            a1[i][j] = data[j-i];
        }else if(j==i){
            a1[i][j] = data[0];
        }else{
            a1[i][j] = data[i-j];
        }
    }