How do I make a lower triangular matrix from a column vector?

47 ビュー (過去 30 日間)
Leo Cordery Smith
Leo Cordery Smith 2021 年 3 月 9 日
コメント済み: Rik 2021 年 3 月 29 日
I am trying to make a lower triangular matrix from a column vector to then produce a fully populated 24x24 symmetric matrix.
The column vector I'm using (A as a simple example) has 300 elements and I need to populate the triangular matrix (B as a simple example) as follows:
A = [i1 i2 i3 i4 i5 i6 i7 i8 i9 i10 ...]
B = [i1; i2 i3; i4 i5 i6; i7 i8 i9 i10; ....]
Any help would be appreciated. It may be that it's easier to make the symmetric matrix straight away, if so I'm open to suggestions. Thanks in advance.

採用された回答

Jan
Jan 2021 年 3 月 9 日
Create the symmetric matrix directly:
n = 24;
Ind = zeros(n, n);
Ind((1:n) >= (1:n).') = 1:300;
Ind = Ind + Ind.' - diag(diag(Ind));
B = A(Ind);
  3 件のコメント
Leo Cordery Smith
Leo Cordery Smith 2021 年 3 月 28 日
Hi Jan, do you know how to write the above code in Python? I've had to change my program from MATLAB to Python. Thanks.
Jan
Jan 2021 年 3 月 29 日
Sorry, I have basic programming skills in Python only. Ask this in a python forum.

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

その他の回答 (1 件)

Rik
Rik 2021 年 3 月 9 日
The functions you should be looking for are tril and triu. You should be using triu, because you seem to want to fill your array in row-major order, while the Matlab default is column-major.
A=1:21;%replace with your data
%sz will only be a positive integer if numel(A) is a triangle number
sz=-0.5+sqrt(0.25-4*0.5*-numel(A));
B=triu(ones(sz));
B(logical(B))=A;
B=B.';
disp(B)
1 0 0 0 0 0 2 3 0 0 0 0 4 5 6 0 0 0 7 8 9 10 0 0 11 12 13 14 15 0 16 17 18 19 20 21
  2 件のコメント
Leo Cordery Smith
Leo Cordery Smith 2021 年 3 月 29 日
Hi Rik, do you know how to write the above code in Python? I've had to change my program from MATLAB to Python. Thanks.
Rik
Rik 2021 年 3 月 29 日
Similar to Jan, my Python skill are only rudimentary. If you are an actual Python user, your success in googling documentation will probably be higher.

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

カテゴリ

Help Center および File ExchangeCall Python from MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by