MATLAB: Need Help making a nxn symmetric matrix

arrayfor loopmatrix

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]

Best Answer

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.