Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a triangular matrix based on a vector, in MATLAB?

Let's say I've got a vector like this one:

A = [101:105]

Which is really:

[ 101, 102, 103, 104, 105 ]

And I'd like to use only vector/matrix functions and operators to produces the matrix:

101 102 103 104 105
102 103 104 105 0
103 104 105 0   0
104 105 0   0   0
105 0   0   0   0

or the following matrix:

101 102 103 104 105
0   101 102 103 104
0   0   101 102 103
0   0   0   101 102
0   0   0   0   101

Any ideas anyone?

(I'm very much a novice in MATLAB, but I've been saddled this stuff...)

like image 624
Shalom Craimer Avatar asked Jun 16 '09 09:06

Shalom Craimer


People also ask

How do you make a triangular matrix in Matlab?

Description. L = tril( A ) returns the lower triangular portion of matrix A . L = tril( A , k ) returns the elements on and below the kth diagonal of A .

How do you create a matrix and a vector in Matlab?

To create an array with four elements in a single row, separate the elements with either a comma ( , ) or a space. This type of array is a row vector. To create a matrix that has multiple rows, separate the rows with semicolons. Another way to create a matrix is to use a function, such as ones , zeros , or rand .

How do you convert a matrix to an upper triangular matrix in Matlab?

U = triu( A ) returns the upper triangular portion of matrix A . U = triu( A , k ) returns the elements on and above the kth diagonal of A .


4 Answers

hankel(A) will get you the first matrix

triu(toeplitz(A)) will get you the second one.

--Loren

like image 114
Loren Avatar answered Nov 01 '22 11:11

Loren


The best solutions are listed by Loren. It's also possible to create these matrices using SPDIAGS:

vec = 101:105;
A = full(spdiags(repmat(vec,5,1),0:4,5,5));  % The second matrix
B = fliplr(full(spdiags(repmat(fliplr(vec),5,1),0:4,5,5)));  % The first matrix

I recall creating banded matrices like this before I found out about some of the built-in functions Loren mentioned. It's not nearly as simple and clean as using those, but it worked. =)

like image 41
gnovice Avatar answered Nov 01 '22 12:11

gnovice


The way I'd go about it is to create a matrix A:

101 102 103 104 105
101 102 103 104 105
101 102 103 104 105
101 102 103 104 105
101 102 103 104 105

And then find a matrix B such that when you multiply A*B you'll get the result you want. Basically do the linear algebra on paper first and then have Matlab do the calculation.

like image 41
Nathan Fellman Avatar answered Nov 01 '22 11:11

Nathan Fellman


For generating such triangular matrices with such a regular pattern, use the toeplitz function, e.g.

m=toeplitz([1,0,0,0],[1,2,3,4])

for the other case, use rot90(m)

like image 22
Jean-marie Becker Avatar answered Nov 01 '22 13:11

Jean-marie Becker