MATLAB: Indexing diagonal elements of a matrix in a loop

diagonal elementselimination

I have an n x n matrix, some of its diagonals are zeros. I need to eliminate the rows and columns corresponding to the diagonal zeros in a loop and retain all other elements. ie, if A=[0 3 5 6 5;3 0 4 7 8;7 9 1 0 3;2 4 6 0 8;1 4 5 7 6],after elimination of rows and columns corresponding to diagonal zeros the answer should be, ans=[1 3;5 6]
anyone please help with appropriate code.

Best Answer

Here's one way:
A=[0 3 5 6 5;3 0 4 7 8;7 9 1 0 3;2 4 6 0 8;1 4 5 7 6]
diagonal = logical(eye(size(A)))
% Find bad rows,columns along the diagonal:
badRows = A(diagonal)==0
% Remove rows:
A(badRows, :) = [];
% Remove bad columns:
A(:, badRows) = []