How do I define this matrix in matlab?

346 Views Asked by At

$$A = \begin{pmatrix} 2 &-1 & 0 & \dots & 0 \\ -1 & 2 & -1 & \ddots & \vdots \\ 0 & \ddots & \ddots & \ddots & 0 \\ \vdots & \ddots & -1 & 2 & -1 \\ 0 & \dots & 0 & -1 & 2 \end{pmatrix} \in \Bbb R^{n \times n}$$

How do I write this matrix in matlab?

3

There are 3 best solutions below

0
On BEST ANSWER

there you are:

A =2*diag(ones(1,n))-diag(ones(1,n-1),-1)-diag(ones(1,n-1),1);

(don't forget to set $n$ before :)

However if you want to evaluate $Av$ for some $v$ you should better not define $A$ and use the relations $$(Av)_i = 2v_i-v_{i-1}-v_{i+1}\qquad \forall 1< i < n$$ $$ (Av)_1 = 2v_{1}-v_2 \qquad (Av)_n= 2v_n-v_{n-1}$$ in your code (it may important for computations speed if $n$ is "large")

4
On

You can use convmtx for that:

n = 5; %// required number of rows
A = convmtx([-1 2 -1], n);
A = A(:,2:end-1)

Example: n=5 produces

A =
     2    -1     0     0     0
    -1     2    -1     0     0
     0    -1     2    -1     0
     0     0    -1     2    -1
     0     0     0    -1     2

If you just want to multiply A times a column vector v, instead of A*v it is more effficient to use

conv(v, [-1 2 -1], 'same')
0
On

Your matrix is a symmetric Toeplitz matrix. There's a toeplitz function in Matlab, so, for example, a 5-by-5 version of your matrix can be created via:

n = 5;
T = toeplitz([2 -1 zeros(1,n-2)])

which returns

T =

     2    -1     0     0     0
    -1     2    -1     0     0
     0    -1     2    -1     0
     0     0    -1     2    -1
     0     0     0    -1     2

Type edit toeplitz in your command window to view the code for this function. The solution by @Surb using diag may be more efficient.

Update

For large $n$, a (5 times) faster way to create such a matrix is via the 'tridiag' option with the gallery (documentation) function, which takes advantage of the the sparsity of this matrix:

T = full(gallery('tridiag',n,1,2,1));

Or, in many cases, you can directly call spdiags (documentation), which will be even faster:

x = zeros(n-1,1)+1;
y = zeros(n,1)+2;
z = x;
T = full(spdiags([[x;0] y [0;z]],-1:1,n,n));