Setting elements of an array to be zero based on the values of a vector
조회 수: 28 (최근 30일)
이전 댓글 표시
I want to take the matrix A (as an example) and set all elements of A that have either their row and/or column as a value in B to be 0. For example:
A = [1 0 0; 0 1 1; 1 1 0]
B = [1 3 5];
Then I should get:
A = [0 0 0; 0 1 1; 0 0 0];
where A(1,1) = A(1,3) = A(3,1) = A(1,5) = A(5,1) = A(3,5) = A(5,3) = 0.
I asked a similar question, but I think I didn't frame it correctly. A(B,B) = 0 doesn't work because the resulting array is larger than the original one.
댓글 수: 3
Matt J
2022년 4월 20일
where A(1,1) = A(1,3) = A(3,1) = A(1,5) = A(5,1) = A(3,5) = A(5,3) = 0.
OK, but in your example A(3,2) has also been reset to zero. Is that a mistake?
채택된 답변
Voss
2022년 4월 20일
A = [1 0 0; 0 1 1; 1 1 0];
B = [1 3 5];
% set all elements in those rows of A, whose index is in B, to zero
A(B(B <= size(A,1)),:) = 0;
% set all elements in those columns of A, whose index is in B, to zero
A(:,B(B <= size(A,2))) = 0;
A
% another way:
A = [1 0 0; 0 1 1; 1 1 0];
A(ismember(1:size(A,1),B),:) = 0;
A(:,ismember(1:size(A,2),B)) = 0;
A
댓글 수: 0
추가 답변 (3개)
Matt J
2022년 4월 20일
A = [1 0 0; 0 1 1; 1 1 0]
B = [1 3 5];
[I,J,S]=find(A);
tf=~(ismember(I,B)|ismember(J,B)); %set these to zero
A=accumarray([I(tf),J(tf)],S(tf), size(A))
댓글 수: 0
Jon
2022년 4월 20일
편집: Jon
2022년 4월 20일
I think you want to look at every possible pair of indices that could be made out of the elements of b and set those elements of A to zero. I assume that pairs that are not in A, e.g. 3,5 would be ignored. If this is the case, then I think in your example you should have the new A given by
A = [1 0 0; 0 1 1; 0 1 0]
rather than
A = [0 0 0; 0 1 1; 0 0 0];
Assuming I understand what you are trying to do correctly here is some code that would do it
A = [1 0 0; 0 1 1; 1 1 0]
b = [1,3,5]
% get all possible pairing from b
C = nchoosek(b,2);
allPairs = [C;fliplr(C)];
% just keep the pairs that are inside of A
[m,n] = size(A) % if A is alway square you could simplify this a little
keep = all([allPairs(:,1)<=m allPairs(:,2)<=n],2)
pairs = allPairs(keep,:);
% get linear indices corresponding to these pairs
ind = sub2ind([m,n],pairs(:,1),pairs(:,2))
% replace these elements in A with zeros
A(ind) = 0
댓글 수: 1
Jon
2022년 4월 21일
Looks like I didn't understand what you were trying to do.
What does it mean when you say
where A(1,1) = A(1,3) = A(3,1) = A(1,5) = A(5,1) = A(3,5) = A(5,3) = 0.
Since A is only a 3 row by 3 column matrix there is no A(1,5), A(5,1), A(3,5) or A(5,3) since all of these have either a 5th row or 5th column that wouldn't be in a 3x3 matrix
참고 항목
카테고리
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!