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

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

 Accepted Answer

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

More Answers (2)

Stephen23
Stephen23 on 11 Nov 2018
Edited: Stephen23 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
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);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!