## How to construct the n*n matrices, like below:

### Shangwen Chen (view profile)

on 11 Nov 2018 at 2:25
Latest activity Commented on by Shangwen Chen

### Walter Roberson (view profile)

I know I can use diag to build that matrices, but I did not figured out how to build like that.

### Walter Roberson (view profile)

on 11 Nov 2018 at 2:30

diag(vector_of_2s) - diag(vector_of_ones, 1) - diag(vector_of_ones, -1)

Shangwen Chen

### Stephen Cobeldick (view profile)

on 11 Nov 2018 at 7:34
Edited by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 11 Nov 2018 at 7:35

>> n = 10;
>> toeplitz([2,-1,zeros(1,n-2)])
ans =
2 -1 0 0 0 0 0 0 0 0
-1 2 -1 0 0 0 0 0 0 0
0 -1 2 -1 0 0 0 0 0 0
0 0 -1 2 -1 0 0 0 0 0
0 0 0 -1 2 -1 0 0 0 0
0 0 0 0 -1 2 -1 0 0 0
0 0 0 0 0 -1 2 -1 0 0
0 0 0 0 0 0 -1 2 -1 0
0 0 0 0 0 0 0 -1 2 -1
0 0 0 0 0 0 0 0 -1 2

Shangwen Chen

### Bruno Luong (view profile)

on 11 Nov 2018 at 7:45

Such matrix is a FEM/discrete laplacian, and I strongly recommend using sparse matrix whene ever solving PDE.
n = ...
S = spdiags(ones(n,1)*[-1 2 1],[-1 0 1],n,n);

Shangwen Chen