MATLAB Answers

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

Asked by Shangwen Chen

### Shangwen Chen (view profile)

on 11 Nov 2018
Latest activity Commented on by Shangwen Chen

### Shangwen Chen (view profile)

on 11 Nov 2018
Accepted Answer by Walter Roberson

### 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.

#### 0 Comments

Sign in to comment.

## 3 Answers

### Walter Roberson (view profile)

Answer by Walter Roberson

### Walter Roberson (view profile)

on 11 Nov 2018
Accepted Answer

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

Shangwen Chen

### Shangwen Chen (view profile)

on 11 Nov 2018
Thanks for your helping!

Sign in to comment.

### Stephen Cobeldick (view profile)

Answer by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 11 Nov 2018
Edited by Stephen Cobeldick

### Stephen Cobeldick (view profile)

on 11 Nov 2018

>> 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

### Shangwen Chen (view profile)

on 11 Nov 2018
Thanks for your helping!

Sign in to comment.

### Bruno Luong (view profile)

Answer by Bruno Luong

### Bruno Luong (view profile)

on 11 Nov 2018

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

### Shangwen Chen (view profile)

on 11 Nov 2018
Thanks for your helping!

Sign in to comment.