Advanced logical matrix indexing
조회 수: 5 (최근 30일)
이전 댓글 표시
Is it possible to use one line of code to achieve the following
given an NxN matrix A construct an N-1xN matrix B where each column _n in B eliminates the _nth element from the _n column in A
e.g.
A = [1 1 1;2 2 2;3 3 3] gives B = [2 1 1;3 3 2]
I can do this in a for-loop, but given MATLAB is really bad at handling these I was hoping there is a faster solution
Thanks,
~K
댓글 수: 0
채택된 답변
James Tursa
2012년 10월 11일
Another variation of Matt J's approach:
B = A(:);
B(1:(N+1):(N*N)) = [];
B = reshape(B,N-1,N);
댓글 수: 2
James Tursa
2012년 10월 11일
I noticed that too, but the result is a 1D vector so you still need the reshape at the end.
추가 답변 (2개)
Matt Fig
2012년 10월 11일
편집: Matt Fig
2012년 10월 11일
Given this array:
A = [1 1 1;2 2 2;3 3 3] % Must be n-by-n
% Remove the ith element of each ith column.
B = reshape(A(~eye(size(A))),size(A,1)-1,size(A,1))
.
.
.
EDIT
One could write a nifty little function to do this:
function A = removediag(A)
% Removes the diagonal elements of a square matrix.
% Author: Matt Fig
S = size(A);
if S(1)~=S(2)
error('REMOVEDIAG is only for square arrays');
end
A = reshape(A(~diag(true(1,S(1)))),S(1)-1,S(1));
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!