I was trying to understand how to store a band matrix, I found an example in the book “C++ and Object Oriented Numeric Computing” but I cannot figure out what’s the purpose of the line bda[i] += P; and this also gives me problems when trying to print the band matrix. Here it is:
int N = 5; //Matrix of NxN
int P = 1; //Left bandwidth
int R = 2; //Right bandwidth
//Matrix A
double A[5][5] = { { 1, 6, 10, 0, 0 },
{ 13, 2, 0, 11, 0 },
{ 0, 14, 3, 8, 12 },
{ 0, 0, 0, 4, 9 },
{ 0, 0, 0, 16, 5 } };
//Allocate memory for rows
double** bda = new double*[N];
for (int i = 0; i < N; i++) {
bda[i] = new double[P + R + 1]; //Allocate memory for cols
bda[i] += P; //What's the purpose of this?
}
This is used for a compact way to store a matrix that has
Pnonzero diagonals to the left of the main diagonal, andRnonzero diagonals to the right, with all other elements being zero. For each row, we only allocate space for theP+R+1elements around the main diagonal.The
bda[i] += Pline makesbda[i]point to an element on the main diagonal. This can make it more convenient to use the matrix:bda[i][0]is on the main diagonal for everyi,bda[i][1]is on the first diagonal to the right,bda[i][-1]is on the first diagonal to the left, etc. This allows you to find elements on the main diagonal or near it without having to addPeach time. Whether this is helpful depends on how you use the matrix.Note that if you do this, you will need to subtract
Pfrombda[i]before youdelete[]it.