首页 > 解决方案 > ismember 只取第一个数字

问题描述

如果我有两个数组

A=[5 5 7 8]
B=[5 7 7]

我想要 A 中 B 的所有位置,除非它们在 A 中被配音,那么我只想要第一个。这意味着我想作为输出:

C=[1 3 3]; %indexes

因为 5 在 A 中的位置 1 而我只想要第一个。数字 7 在数组 A 中的位置 3 并在数组 B 中出现两次。这样:A(C)=B

我尝试了下面的代码,但它只处理在 A 中出现 dubbles 的情况下取第一个。不幸的是,它还删除了 B 中 dubbles 的位置。

[ifM,posfM]=ismember(A,B);%find position where B is in A
nuls=find(posfM==0);%positions where this is not the case
[Ci,iafM,ic] = unique(posfM);% make sure the same number is only selected once (A=[1 1 2 3],B=[1 3] creates three numbers if ismember(A,B) and we only need two) 
posnuls=ismember(iafM,nuls);
iafM(posnuls)=[];
fBM=fMag(iafM);

标签: matlab

解决方案


简单地循环B,并为 B 中的每个元素找到其第一次出现的索引:

>> C = arrayfun(@(x) find(A==x,1),B);

推荐阅读