简体   繁体   English

在另一个矩阵matlab中删除具有相应零的元素

[英]remove elements with corresponding zeros in another matrix matlab

I have two matrices A & B in Matlab, for example 例如,我在Matlab中有两个矩阵A和B

A=[0,0,1,2,3,0,4,2,0]
B=[2,3,1,2,2,3,4,4,1]

What I want to do is to set elements in B to zero where they have the same position as zero elements in A. So in my example: 我想做的是将B中的元素设置为零,使其与A中的零元素具有相同的位置。因此在我的示例中:

A=[0,0,1,2,3,0,4,2,0]
B=[2,3,1,2,2,3,4,4,1]

I want B to be like this: 我希望B像这样:

B=[0,0,1,2,2,0,4,4,0]

Any idea? 任何想法?

You can do it using logical indexing like so: B(A==0) = 0 您可以像这样使用逻辑索引进行操作B(A==0) = 0

EDIT: 编辑:

You can also do it like this: B.*(A~=0) which will be easier to generalise to higher dimensions using bsxfun as per your comment below. 您也可以这样做: B.*(A~=0) bsxfun B.*(A~=0) ,根据下面的评论,使用bsxfun可以更容易地将其推广到更高的尺寸。

The only problem with doing something that Dan suggests is if A and B are not the same size. Dan建议做的事情的唯一问题是A和B的大小是否不相同。 You can still however do this with a little bit of extra work. 但是,您仍然可以做一些额外的工作。

indices = find(A==0);
indices = indices(indices <= length(B));
B(indices) = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM