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 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Margaret Mora
el 22 de En. de 2022
Comentada: Voss
el 22 de En. de 2022
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
0 comentarios
Respuesta aceptada
Voss
el 22 de En. de 2022
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);
% 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);
% 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);
% 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)
4 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Operating on Diagonal Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!