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

Dan*_*Dan 5 matlab find cell-array

A = {'A'; 'E'; 'A'; 'F'};

B = {'A';'B';'C';'D';'E'; 'F'};
Run Code Online (Sandbox Code Playgroud)

我试图获取单元格数组中的每个字符串A,该索引与单元格数组中的该字符串匹配B.A会有重复的价值,B不会.

find(ismember(B, A) == 1)
Run Code Online (Sandbox Code Playgroud)

输出

1
5
6 
Run Code Online (Sandbox Code Playgroud)

但我想得到

1
5
1
6
Run Code Online (Sandbox Code Playgroud)

优选地在一个衬里中.我不能使用strcmp而不是ismember,因为向量是不同的大小.

向量实际上将包含日期字符串,我需要索引不是逻辑索引矩阵,我对不使用它进行索引的数字感兴趣.

我该怎么做?

Jon*_*nas 7

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

[~,loc]=ismember(A,B)

loc =

     1
     5
     1
     6
Run Code Online (Sandbox Code Playgroud)

第二个输出告诉您元素的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};
Run Code Online (Sandbox Code Playgroud)

  • 我可以取消删除我的答案,但_this_解决方案是正确的答案.乔纳斯+1. (3认同)