Borrar filtros
Borrar filtros

get a diagonal line in matrix

4 visualizaciones (últimos 30 días)
dao
dao el 21 de Ag. de 2017
Comentada: dao el 22 de Ag. de 2017
Hi, please help me get a diagonal line in matlab. Example, I have a matrix: a = [1 2 3; 4 5 6; 7 8 9] I want to get vector b =[3 5 7] which is a diagonal line of matrix a. This is my code but it doesn't work
a=[1 2 3; 4 5 6; 7 8 9];
b = zeros(1,3);
for i=1:3
for i=1:3
b = a(i,j);
end
end

Respuesta aceptada

Jan
Jan el 21 de Ag. de 2017
Editada: Jan el 21 de Ag. de 2017
Or:
a = [1 2 3; 4 5 6; 7 8 9];
s = size(a);
index = (numel(a) - s(1) + 1):(1 - s(1)):s(2);
b = a(index)
[EDITED, works with non square matrices now]
  3 comentarios
Jan
Jan el 22 de Ag. de 2017
If you really want a loop:
b = zeros(1,3);
for i = 1:3
b(i) = a(i, 4 - i);
end
dao
dao el 22 de Ag. de 2017
Thank you for your answer, it is neat. in my case, the column and row are equal. How about they are different. Example, I have a matrix 3x4 ? Do I need to use two loop ?

Iniciar sesión para comentar.

Más respuestas (1)

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by