MATLAB Answers

0

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

Asked by Shangwen Chen on 11 Nov 2018 at 2:25
Latest activity Commented on by Shangwen Chen about 23 hours ago
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

Answer by Walter Roberson
on 11 Nov 2018 at 2:30
 Accepted Answer

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

  1 Comment

Thanks for your helping!

Sign in to comment.


Answer by Stephen Cobeldick on 11 Nov 2018 at 7:34
Edited by Stephen Cobeldick 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

  1 Comment

Thanks for your helping!

Sign in to comment.


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

  1 Comment

Thanks for your helping!

Sign in to comment.