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

2 views (last 30 days)
I know I can use diag to build that matrices, but I did not figured out how to build like that.

Accepted Answer

Walter Roberson
Walter Roberson on 11 Nov 2018
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

Bruno Luong
Bruno Luong 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);

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!