How to covert a vector of lower triangular matrix factors back to the original matrix?
8 views (last 30 days)
Show older comments
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!!
0 Comments
Accepted Answer
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);
2 Comments
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
More Answers (2)
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
0 Comments
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.
2 Comments
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.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!