How do I build this band matrix in MATLAB?

4.8k Views Asked by At

I need to build a pentadiagonal matrix in MATLAB like this:

$\begin{pmatrix} 1+2\lambda & -\lambda_1 & 0 & -\lambda_1 & 0 & \cdots & 0\\ -\lambda_1 & 1+4\lambda_1 & -\lambda_1 & 0 & -\lambda_1 & \cdots & 0\\ 0 & -\lambda_1 & 1+4\lambda_1 & -\lambda_1 & 0 & \cdots & -\lambda_1\\ -\lambda_1 & 0 & -\lambda_1 & 1+4\lambda_1 & -\lambda_1 & \cdots & 0\\ 0 & -\lambda_1 &0 & -\lambda_1 & 1+4\lambda_1 & \cdots & -\lambda_1 \\ \vdots & \vdots &\vdots & \vdots & \vdots & \ddots & \vdots\\ 0 & 0 & -\lambda_1 & 0 & -\lambda_1 & \cdots & 1+2\lambda_1\end{pmatrix}$

And once a have this pentadiagional matrix, then I have to build a similar matrix like this:

$\begin{pmatrix} 1-2\lambda & \lambda_1 & 0 & \lambda_1 & 0 & \cdots & 0\\ \lambda_1 & 1-4\lambda_1 & \lambda_1 & 0 & \lambda_1 & \cdots & 0\\ 0 & \lambda_1 & 1-4\lambda_1 & \lambda_1 & 0 & \cdots & \lambda_1\\ \lambda_1 & 0 & \lambda_1 & 1-4\lambda_1 & \lambda_1 & \cdots & 0\\ 0 & \lambda_1 &0 & \lambda_1 & 1-4\lambda_1 & \cdots & \lambda_1 \\ \vdots & \vdots &\vdots & \vdots & \vdots & \ddots & \vdots\\ 0 & 0 & \lambda_1 & 0 & \lambda_1 & \cdots & 1-2\lambda_1\end{pmatrix}$

O know how to build a tridiagonal matrix whit the next code:

    lambda1 = dt.*Du./(2.*dx.^2);
  Au = eye(Nx).*(1+2.*lambda1);
  Au(1+1:Nx+1:end) = -lambda1;
  Au(Nx+1:Nx+1:end) = -lambda1;
  Au([1,end]) = 1+lambda1;

where $Nx$ is the size of the matrix and $\lambda_1$ is a constant. How can I build this pentadiagonla matrix with this entries?

2

There are 2 best solutions below

6
On

You can write it as a sum of "diag" commands. For example the code

diag([1,1,1],2) + diag([2,2,2,2],1) + diag([3,3,3,3,3],0)

gives

$$\left[\begin{array}{ccccc}3&2&1&0&0\\0&3&2&1&0\\0&0&3&2&1\\0&0&0&3&2\\0&0&0&0&3\end{array}\right]$$

of course you can just replace the vectors by "scalar_value * ones(1,N-k)", where k is by how much off the main diagonal we are and N is the dimension of the matrix. For example

diag(-lambda_1*ones(1,N-1),1)

Edit if the matrix is going to be very large you may want it to be sparse as many calculations will get faster and will take much less memory for storage, you can then use the sparse command:

sparse(rows_,cols_,vals_,N,N)

Where the value in vals_(i) will get in position (rows_(i),cols_(i)). Will probably be necessary if matrix larger than a side of thousands or tens of thousands.

2
On

That band matrix is almost a Toeplitz matrix. It is also symmetric. Hence,

r = [1+4*lambda1, -lambda1, 0, -lambda1, zeros(1,n-4)];
A = toeplitz(r);

Update now the northwest and southeast corners:

A(1,1) = 1+2*lambda1;
A(n,n) = 1+2*lambda1;