Need Help making a nxn symmetric matrix

1 view (last 30 days)
My symmetric matrix should look like
[1 0 0 0 0..n no. of zeroes;
1 -2 1 0 0 0..n;
0 1 -2 1 0 0 ..;
for n no of rows]
  1 Comment
James Tursa
James Tursa on 13 Nov 2015
Edited: James Tursa on 13 Nov 2015
Are the last two rows this?
0 ... 0 1 -2 1;
0 ... 0 0 0 1];
Or this?
0 ... 0 1 -2 1;
0 ... 0 0 1 -2];
Is this an n X n matrix or an n X n+1 matrix? It is not clear from your example what the matrix should really look like since your example is not symmetric (e.g., the (2,1) spot is not equal to the (1,2) spot)

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 13 Nov 2015
Edited: James Tursa on 13 Nov 2015
Making a guess at what you really want, you could build it in pieces, e.g.,
n = size of matrix;
A = zeros(n);
A(1:n+1:end) = -2; % The diagonal
A(2:n+1:end) = 1; % The lower diagonal
A(n+1:n+1:end) = 1; % The upper diagonal
A(1,1) = 1; % Different value for the (1,1) spot.
An alternative method could employ the spdiags function to build the matrix.
  2 Comments
Nitesh Panchal
Nitesh Panchal on 13 Nov 2015
Few twitches and it worked perfectly thank you
Stephen23
Stephen23 on 14 Nov 2015
See my answer for a much simpler way to create this matrix.

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 14 Nov 2015
Edited: Stephen23 on 14 Nov 2015
Simply use toeplitz:
>> n = 6;
>> M = toeplitz([-2,1,zeros(1,n-2)]);
>> M(1) = 1; M(end) = 1
M =
1 1 0 0 0 0
1 -2 1 0 0 0
0 1 -2 1 0 0
0 0 1 -2 1 0
0 0 0 1 -2 1
0 0 0 0 1 1
  1 Comment
Nitesh Panchal
Nitesh Panchal on 14 Nov 2015
It was pretty simple but harder to comprehend , i tried using this command but i couldnt figure it out , but thank you so much

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!