查找单元格数组中所有(非唯一)元素的索引,因为它们出现在第二个(排序和唯一)单元格数组中


A = {'A'; 'E'; 'A'; 'F'};
B = {'A';'B';'C';'D';'E'; 'F'};

我正在尝试获取单元格数组A中的每个字符串,与单元格数组B中的该字符串匹配的索引。 A将具有重复的值,B不会。

find(ismember(B, A) == 1)

输出

1
5
6 

但我想得到

1
5
1
6

最好是单衬。我也不能使用 strcmp 代替 ismember,因为矢量的大小不同。

向量实际上将包含日期字符串,我需要索引而不是逻辑索引矩阵,我对数字感兴趣,不要将其用于索引。

我该怎么做?

参数翻转为 ismember ,并使用第二个输出参数:

[~,loc]=ismember(A,B)
loc =
     1
     5
     1
     6

第二个输出告诉您A元素在B中的位置。

如果您对代码中可以包含的行数有非常严格的限制,并且无法解雇施加此类限制的管理器,则可能需要直接访问ismember的第二个输出。为此,您可以创建以下帮助程序函数,该函数允许直接访问函数的第 i 个输出

function out = accessIthOutput(fun,ii)
%ACCESSITHOUTPUT returns the i-th output variable of the function call fun
%
% define fun as anonymous function with no input, e.g.
% @()ismember(A,B)
% where A and B are defined in your workspace
%
% Using the above example, you'd access the second output argument
% of ismember by calling
% loc = accessIthOutput(@()ismember(A,B),2)

%# get the output
[output{1:ii}] = fun();
%# return the i-th element
out = output{ii};

最新更新