Borrar filtros
Borrar filtros

Exclude matrix diagonal in for loop

5 visualizaciones (últimos 30 días)
Fred John
Fred John el 9 de Mzo. de 2015
Editada: Michael Haderlein el 9 de Mzo. de 2015
Hi,
Let's say I have a 20x20 matrix for which I wish to run some formulas over a loop. But I wish to exclude the main diagonal (1,1 to 20,20) from the for loop.
I came up with:
for j=2:20
for i:(j-1)
Any thoughts please?
Thanks

Respuestas (2)

Guillaume
Guillaume el 9 de Mzo. de 2015
Editada: Guillaume el 9 de Mzo. de 2015
Your second for is not going to do much. This is one way to do it:
for row = 1:size(matrix, 1) %use better names than i or j and don't hardcode sizes
for col = 1:size(matrix, 2)
if col ~= row %if not on diagonal
%do calculation
end
end
end
However, if you can vectorise your calculation and forego the loops entirely that would be even better.

Michael Haderlein
Michael Haderlein el 9 de Mzo. de 2015
Editada: Michael Haderlein el 9 de Mzo. de 2015
In case you cannot vectorize the problem, why don't you simply check for equality?
for cnt1 = 1:20
for cnt2=1:20
if cnt1~=cnt2
%calculations
end
end
end

Categorías

Más información sobre Loops and Conditional Statements 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