indexing diagonal elements of a matrix in a loop

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.

 Accepted 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) = []

2 Comments

I hope this wasn't homework. Though I didn't use a loop like you were instructed, so I guess it's safe. But you can see the concept of setting the row or column to [] to remove it - that's the main thing you want to remember, though it might be better to build up a separate "B" output matrix as you go along and encounter "good" rows and columns.

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!