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.

 채택된 답변

Image Analyst
Image Analyst 2013년 6월 2일

0 개 추천

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

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.
Thanks a lot :)

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

카테고리

도움말 센터File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by