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

8 次查看(过去 30 天)
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
Andrei Bobrov 2014-9-16
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 个评论
Wenyu Cheng
Wenyu Cheng 2020-6-11
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

请先登录,再进行评论。

更多回答(2 个)

Yu Jiang
Yu Jiang 2014-8-29
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
Roger Stafford 2014-8-30
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 个评论
Jason
Jason 2014-9-4
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
Roger Stafford 2014-9-4
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by