I want to create a matrix combining 2 matrices. The new one must have from the diagonal up de elements of matrix A and from the diagonal down the elements of matrix B. Help

조회 수: 2 (최근 30일)
I want to create a matrix combining 2 matrices. The new one (matrix C) must have from the diagonal up de elements of matrix A and from the diagonal down the elements of matrix B. Both matrices A and B have 0 in the diagonal, they have the same size and are simetric. Can anyone help with the code for that? Thank you

채택된 답변

Voss
Voss 2022년 1월 22일
You can use triu() and tril() to get upper- and lower-triangular matrices, respectively, and logical indexing to combine them:
% Create some symmetric matrices:
A = [0 1 2; 1 0 3; 2 3 0];
B = 10*A;
display(A); display(B);
A = 3×3
0 1 2 1 0 3 2 3 0
B = 3×3
0 10 20 10 0 30 20 30 0
% get upper-triangular matrix of A:
A_tri = triu(A);
% get lower-triangular matrix of B:
B_tri = tril(B);
display(A_tri); display(B_tri);
A_tri = 3×3
0 1 2 0 0 3 0 0 0
B_tri = 3×3
0 0 0 10 0 0 20 30 0
% get logical matrix where A_tri is non-zero:
A_idx = logical(A_tri);
% get logical matrix where B_tri is non-zero:
B_idx = logical(B_tri);
display(A_idx); display(B_idx);
A_idx = 3×3 logical array
0 1 1 0 0 1 0 0 0
B_idx = 3×3 logical array
0 0 0 1 0 0 1 1 0
% make a new matrix C and fill in the upper and lower triangular parts using the logical matrices:
C = zeros(size(A));
C(A_idx) = A(A_idx);
C(B_idx) = B(B_idx);
display(C)
C = 3×3
0 1 2 10 0 3 20 30 0
  댓글 수: 4
Voss
Voss 2022년 1월 22일
Welcome, and thank you! Any other questions, feel free to post them

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by