Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a lower triangular matrix from a given vector

My problem is the following: I have a vector as

[3,4,5,6,7]

I want to create a matrix as

3 0 0 0 0   
3 4 0 0 0   
3 4 5 0 0   
3 4 5 6 0   
3 4 5 6 7 

However, I don't want to use for loops because of the problem of size that I will eventually get. I was thinking about using flipud, fliprl, hankel and toeplitz functions but cannot find a solution.

like image 400
emper Avatar asked Jan 29 '26 13:01

emper


2 Answers

Try this:

x = [3,4,5,6,7]
tril(ones(length(x),1)*x)

ans =

 3     0     0     0     0
 3     4     0     0     0
 3     4     5     0     0
 3     4     5     6     0
 3     4     5     6     7
like image 61
rasmus Avatar answered Feb 01 '26 07:02

rasmus


If A is your vector, you can do

M=repmat(A, length(A), 1) .* tril(ones(length(A),length(A)),0)

like image 22
Diego Avatar answered Feb 01 '26 07:02

Diego



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!