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

2 次查看(过去 30 天)
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

采纳的回答

Matt J
Matt J 2022-4-20
  4 个评论
L'O.G.
L'O.G. 2022-4-20
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 2022-4-20
编辑:Matt J 2022-4-20
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by