How can i build a symmetric matrix from a vector ?

18 ビュー (過去 30 日間)
sajjad
sajjad 2015 年 8 月 21 日
回答済み: Moe Money 2017 年 6 月 12 日
assume i have a 1*n vector like x = [1 2 3 4 5 6], i want to reshape this vector to a symmetric matrix like
symx = [1 2 3; 2 4 5; 3 5 6];
or something like this:
symx = [1 4 6; 4 2 5; 6 5 3];
Thanks for your help
  1 件のコメント
John D'Errico
John D'Errico 2015 年 8 月 21 日
Sorry, but unless you give the rules by which you have chosen to call that a "reshape" where you take 6 numbers and somehow magically decide to reshape them into a 9 element array, then nobody can help you. The mind reading toolbox is still in beta test.

サインインしてコメントする。

採用された回答

Moe Money
Moe Money 2017 年 6 月 12 日
I used the functions SQUAREFORM and DIAG
Example: Imagine you want to create a symmetric 4x4 matrix. You need a vector with 10 elements.
>> n=4;
>> vec=[1:10]';
>> sqmat = diag(vec(1:n)) + squareform(vec(n+1:end))
sqmat =
1 5 6 7
5 2 8 9
6 8 3 10
7 9 10 4

その他の回答 (2 件)

Steven Lord
Steven Lord 2015 年 8 月 21 日
The SQUAREFORM function from Statistics and Machine Learning Toolbox gets close, but it puts zeros on the diagonal and fills in the upper and lower triangles, which is not quite what you're asking for but is close. In order to do what you're asking, you can use logical indexing.
x = 1:6;
y = zeros(3);
upperTriangleIndices = triu(true(3));
y(upperTriangleIndices) = x; % Fill in the upper piece
y = y + y.' - diag(diag(y)) % Mirror the upper piece to the lower, which doubles the diagonal
% so subtract off the diagonal
  2 件のコメント
sajjad
sajjad 2015 年 8 月 21 日
Thanks, Steven i think i find the way just when i send my question to the forum, the answer is using the vec2sm function.
Moe Money
Moe Money 2017 年 6 月 12 日
Steven: I had a similar question and the function SQUAREFORM solved my problem. Thanks a lot!

サインインしてコメントする。


Walter Roberson
Walter Roberson 2015 年 8 月 21 日

カテゴリ

Help Center および File ExchangeVector Spaces and Subspaces についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by