Setting elements of an array to be zero based on the values of a vector
Show older comments
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 Comments
A = [1 0 0; 0 1 1; 1 1 0]
B = [1 3 5];
A = [0 0 0; 0 1 1; 0 0 0]
Why does A(2,3) not get set to 0?
It's in column 3, which is an element of B, so it seems like it should be set to 0.
Matt J
on 20 Apr 2022
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?
L'O.G.
on 20 Apr 2022
Accepted Answer
More Answers (3)
A = [1 0 0; 0 1 1; 1 1 0]
B = [1 3 5];
[m,n]=size(A);
I=B(B<=m);
J=B(B<=n);
A(I,:)=0;
A(:,J)=0
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))
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 Comment
Jon
on 21 Apr 2022
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
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!