How to add zeros diagonally in a matrix?

5 visualizaciones (últimos 30 días)
ASHA PON
ASHA PON el 14 de Dic. de 2022
Comentada: ASHA PON el 14 de Dic. de 2022
I am having a 4*5 matrix. Now, I need to add '0' diagonally and convert the matrix into 5*5. Thank you in advance.
Example:
A=[2 2 1 3 2
1 3 3 1 2
3 1 4 4 1
2 2 1 3 3]
Expected output:
B=[ 0 2 1 3 2
2 0 3 1 2
1 3 0 4 1
3 1 4 0 3
2 2 1 3 0]

Respuesta aceptada

Stephen23
Stephen23 el 14 de Dic. de 2022
A = [2,2,1,3,2;1,3,3,1,2;3,1,4,4,1;2,2,1,3,3]
A = 4×5
2 2 1 3 2 1 3 3 1 2 3 1 4 4 1 2 2 1 3 3
S = size(A)+[1,0];
B = zeros(S);
B(~eye(S)) = A
B = 5×5
0 2 1 3 2 2 0 3 1 2 1 3 0 4 1 3 1 4 0 3 2 2 1 3 0
  1 comentario
ASHA PON
ASHA PON el 14 de Dic. de 2022
Thank you for the reply. This is what i needed.

Iniciar sesión para comentar.

Más respuestas (1)

Jiri Hajek
Jiri Hajek el 14 de Dic. de 2022
Hi, MATLAB has functions that can extract upper and lower triangular parts of a matric, rest is just adding them into a zero pre-allocated matrix B:
A = randn(4)
Au = triu(A);
Al = tril(A);
B = zeros(5);
B(1:4,2:end) = Au;
B(2:end,1:4) = B(2:end,1:4)+Al
  1 comentario
ASHA PON
ASHA PON el 14 de Dic. de 2022
Thank you for the reply. But i am getting error in matrix dimension mismatch.

Iniciar sesión para comentar.

Categorías

Más información sobre Operating on Diagonal Matrices en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by