# Nearly diagonal matrix

1. Nov 16, 2008

### realanony87

I am trying to create the following Matrix without the use of a for loop.
1 2 1 0 0 0 0 0 0 0 0 0
0 0 1 2 1 0 0 0 0 0 0 0
0 0 0 0 1 2 1 0 0 0 0 0
0 0 0 0 0 0 1 2 1 0 0 0
Etc.
Is there a simple way of doing this

Edit: Using Matlab

Last edited: Nov 16, 2008
2. Nov 16, 2008

### f95toli

Are you using Matlab?
You have a tridiagonal matrix so the easiest way to set it up is to add 3 diagonal matrices.

If you have an m-by-m matrix you can write

diag(2*ones(1,m),0) + diag(ones(m-1,1),1) + diag(ones(m-1,1),-1)

Note that this matrix will have a 2 at the first and last position of the main diagonal, but you can easily remove the first and last row.

3. Nov 16, 2008

### realanony87

Well It isn't tridiagonal because every row is shifted to the left by one .

4. Nov 17, 2008

### matematikawan

Simply cannot resist the opportunity for me to practise writing a matlab script

% will display m by n matrix B that wrapped the elements 1 2 1

m=5; n=10;
A=zeros(1,n);
A(1)=1; A(2)=2; A(3)=1;

for k=1:m
B(k,:)=circshift(A,[1 k-1]);
end
B