Clear Filters
Clear Filters

Setting an element of an array to zero based on the values of a vector

2 views (last 30 days)
Given a 2D array with elements a(i,j), if either i or j matches any element in another vector, how do you set the value for that a(i,j) = 0?
So, for example, given A = magic(5), how do you set to 0 any element of A given a vector B = [1 2 5 8] if 1, 2, 5, or 8 is an entry in A?
Here, I want to obtain:
A =
17 24 0 0 15
23 0 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 0 9

Accepted Answer

Matt J
Matt J on 20 Apr 2022
  4 Comments
L'O.G.
L'O.G. on 20 Apr 2022
I suppose I didn't put it well. I meant in this case, A(1,1) = 17, but 17 is not in B and therefore A(1,1) should be left as it is.
Matt J
Matt J on 20 Apr 2022
Edited: Matt J on 20 Apr 2022
A = magic(5),
A = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
B = [1 2 5 8];
A( ismember(A,B) )=0
A = 5×5
17 24 0 0 15 23 0 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 0 9

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!