This time I will show you how to solve simultaneous linear equations with a tridiagonal matrix.
The content is as follows.
I also have other articles here about simulation.
Tridiagonal matrix
In linear algebra, a tridiagonal matrix is a band matrix that has nonzero elements on the main diagonal, the first diagonal below this, and the first diagonal above the main diagonal only. (Wikipedia)
All elements in the empty space are zero.
A simultaneous linear equation with a tridiagonal matrix as the coefficient matrix can be solved by \(O\left(n\right)\) (\(n\) is the matrix size).
I will introduce it here.
The way to solve
We consider solving a simultaneous linear equation
here, \({\bf x},\,{\bf d}\) are both \(n\) dimensional vectors.
Jumping right to the conclusion, with \(P_{i},\,Q_{i}\) that satisfy
it can be solved as
First, we look at the first line.
From
we get
Now, for later use, let \( P_{1} = -c_{1}/b_{1},\,Q_{1} = d_{1}/b_{1}\), then we can write
Next, the second line.
Substituting the above \(x_{1}\) and organizing,
here,
Repeating the same thing, up to the \(\left(n-1\right)\)-th line,
Lastly, the \(n\)-th line is
but the equation of the \(\left(n-1\right)\)-th line
gives us the following result,
After all, we can get the answer \(x_{i}\) with \(O\left(n\right)\) calculations by finding \(P_{i},\,Q_{i}\) in the previous calculation.
Implementation example
void trimat_sol(double **A,double *a,double *u,int n){
A[0][1] = -A[0][1];
for(int i = 1;i<n-1;i++){
A[i][i-1] = -A[i][i-1];
A[i][i+1] = -A[i][i+1];
}
A[n-1][n-2] = -A[n-1][n-2];
double *P,*Q;
if((P = (double *)malloc(sizeof(double)*n))==NULL){
printf("*** Allocation ERROR P ***\n");
exit(1);
}
if((Q = (double *)malloc(sizeof(double)*n))==NULL){
printf("*** Allocation ERROR Q ***\n");
exit(1);
}
double den;
double num;
P[0] = A[0][1]/A[0][0];
Q[0] = a[0]/A[0][0];
for(int i = 1;i<n;i++){
den = A[i][i]-A[i][i-1]*P[i-1];
P[i] = A[i][i+1]/den;
num = a[i]+A[i][i-1]*Q[i-1];
Q[i] = num/den;
}
u[n-1] = Q[n-1];
for(int i = n-2;i>=0;i--){
u[i] = P[i]*u[i+1]+Q[i];
}
free(P);
free(Q);
}
An exercise
Given matrix \(A\), solve the equation
with \(A\) and \(d\)
The answer;
Summary
Now, that’s all what I wanted to write.
This time, I introduced a way to solve a simultaneous linear equation with a tridiagonal coefficient matrix.
Thank you for reading and please spread this blog if you like.
If you have any comment, please let me know from the e-mail address below or the CONTACT on the menu bar.
tsunetthi(at)gmail.com
Please change (at) to @.
Or you can also contact me via twitter (@warotan3)