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

조회 수: 19 (최근 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
Wenyu Cheng
Wenyu Cheng 2020년 6월 11일
Ah, just figured out that we could use tril instead.

댓글을 달려면 로그인하십시오.

추가 답변 (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에서 Particle & Nuclear Physics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by