How I create matrix below from vector [1 2 3 4 5]
1 0 0 0 0
2 1 0 0 0
3 2 1 0 0
4 3 2 1 0
5 4 3 2 1
0 5 4 3 2
0 0 5 4 3
0 0 0 5 4
0 0 0 0 5
How I create matrix below from vector [1 2 3 4 5]
1 0 0 0 0
2 1 0 0 0
3 2 1 0 0
4 3 2 1 0
5 4 3 2 1
0 5 4 3 2
0 0 5 4 3
0 0 0 5 4
0 0 0 0 5
This is not tridiagonal, but a variant of pentadiagonal matrix. You can use diag, or sparse, or spdiags, all of which could build it. You could read my blktridiag code, as found on the File Exchange, to learn how I build such a matrix efficiently.
But perhaps the simplest solution is to recognize that your matrix is of a special form, a toeplitz matrix.
>> toeplitz([1:5,zeros(1,4)]',[1, zeros(1,4)])
ans =
1 0 0 0 0
2 1 0 0 0
3 2 1 0 0
4 3 2 1 0
5 4 3 2 1
0 5 4 3 2
0 0 5 4 3
0 0 0 5 4
0 0 0 0 5
Not sure exactly what you are trying to do, but you may find diag(v,n)
and convmtx(v)
useful. In your case
convmtx([1,2,3,4,5],5)
Produces:
1 2 3 4 5 0 0 0 0
0 1 2 3 4 5 0 0 0
0 0 1 2 3 4 5 0 0
0 0 0 1 2 3 4 5 0
0 0 0 0 1 2 3 4 5
take a look here: http://www.mathworks.com/help/techdoc/ref/diag.html
Example:
diag(-m:m)+diag(ones(2*m,1),1)+diag(ones(2*m,1),-1)
produces a tridiagonal matrix of order 2*m+1.