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

18 ビュー (過去 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 Center および File ExchangeParticle & Nuclear Physics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by