# How to covert a vector of lower triangular matrix factors back to the original matrix?

20 views (last 30 days)
Jason on 29 Aug 2014
Commented: Wenyu Cheng on 11 Jun 2020
Hi guys
Could you pleas offer me some help with how to covert a vector to a matrix?
for example, the vector I have is [ 1 2 2 3 5 3 4 9 8 4]
And the desirable result is:
1 2 3 4
2 2 5 9
3 5 3 8
4 9 8 4
The vector I have is actually the factors of the lower triangular matrix of a covariance matrix, right now I want to convert it back to the original covariance matrix. The actual length of the vector I have is like 70,000+ ...
Thx a lot!!

Andrei Bobrov on 16 Sep 2014
p = [ 1 2 2 3 5 3 4 9 8 4];
a = triu(ones(4));
a(a > 0) = p;
out = (a + a')./(eye(4)+1);
Wenyu Cheng on 11 Jun 2020
This is a nice solution. Thank you for sharing it!
I wonder whether it's possible to go row-wise to have the final output as below after the third line of your code?
1 2 2 3
0 5 3 4
0 0 9 8
0 0 0 4
Wenyu Cheng on 11 Jun 2020
Ah, just figured out that we could use tril instead.

Yu Jiang on 29 Aug 2014
May not be the optimal solution, by you can try
p = [ 1 2 2 3 5 3 4 9 8 4];
n = 4;
P = zeros(n,n);
k = 1;
for i = 1:n
for j = 1:i
P(i,j) = p(k);
if i~=j
P(j,i) = p(k);
end
k = k +1;
end
end

Roger Stafford on 30 Aug 2014
I assume we have n where the desired matrix is to be of size n x n and the vector v which must be of length n*(n+1)/2.
A = triu(ones(n));
A(A~=0) = 1:n*(n+1)/2;
A = A + triu(A,1).';
A = reshape(v(A),n,n);
A should be the requested matrix.
Jason on 4 Sep 2014
Hi Roger, it seems good, One question, somehow, my matlab does not have solve function, so I can not use solve function to calculate n(size of matrix) based on v (length of the vector), is there any way around it? Thank you very much!
Roger Stafford on 4 Sep 2014
You don't need 'solve' for a simple problem like that. If your vector is of length m, then you need to solve the equation m = n*(n+1)/2 for n. Its solution would be:
n = (-1+sqrt(1+8*m))/2
If your vector is of valid length corresponding to the number of elements in the upper part of a square matrix, then 1+8*m must be a perfect square of an odd integer, so the n you derive will indeed be an integer. Otherwise you don't have a valid vector length.