matlab - 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);
解决方案
简单地循环B
,并为 B 中的每个元素找到其第一次出现的索引:
>> C = arrayfun(@(x) find(A==x,1),B);
推荐阅读
- typescript - 如何在 TS 中扁平化 obj
- python - 在 python 代码中出现“NoReverseMatch”错误
- r - 使用 R 获取该期间的所有周数
- laravel - Laravel 添加/删除输入字段更新值问题
- javascript - Javascript - 如果子字符串前面没有添加字符 Regex 或其他字符,则替换子字符串
- java - 从 Netlogo 扩展分别返回多个值
- django - 如何在 Django-summernote 中附加图像文件?
- r - 基于 Shiny 中最近输出的自动滚动
- c# - 在 C# 中清除 flowlayoutpanel 控件时创建窗口句柄时出错?
- gradle - 如何使用 Gradle 设置多项目 IntelliJ 工作区?