如果您查看第一个输出,ismember 将为您提供所有索引:
>> x = [1 2 2 3 3 3 4 5 6 7 7];
>> [tf,loc]=ismember(x,3);
>> inds = find(tf)
inds =
4 5 6
您只需要使用正确的输入顺序。
请注意,ismember 使用的辅助函数可以直接调用:
% ISMEMBC - S must be sorted - Returns logical vector indicating which
% elements of A occur in S
tf = ismembc(x,3);
inds = find(tf);
使用ismembc 将节省计算时间,因为ismember 首先调用issorted,但这将省略检查。
请注意,较新版本的 matlab 有一个由 builtin('_ismemberoneoutput',a,b) 调用的内置函数,具有相同的功能。
由于ismember 等的上述应用有些倒退(在第二个参数中搜索x 的每个元素而不是相反),因此代码比必要的要慢得多。正如 OP 指出的那样,不幸的是,[~,loc]=ismember(3,x) 仅提供了 3 在x 中第一次出现的位置,而不是全部。但是,如果您有最新版本的 MATLAB(我认为是 R2012b+),您可以使用更多未记录的内置函数来获取第一个和最后一个索引!这些是ismembc2 和builtin('_ismemberfirst',searchfor,x):
firstInd = builtin('_ismemberfirst',searchfor,x); % find first occurrence
lastInd = ismembc2(searchfor,x); % find last occurrence
% lastInd = ismembc2(searchfor,x(firstInd:end))+firstInd-1; % slower
inds = firstInd:lastInd;
仍然比 Daniel R. 出色的 MATLAB 代码慢,但它(rntmX 添加到 randomatlabuser 的基准测试中)只是为了好玩:
mean([rntm1 rntm2 rntm3 rntmX])
ans =
0.559204323050486 0.263756852283128 0.000017989974213 0.000153682125682
以下是ismember.m 中这些函数的一些文档:
% ISMEMBC2 - S must be sorted - Returns a vector of the locations of
% the elements of A occurring in S. If multiple instances occur,
% the last occurrence is returned
% ISMEMBERFIRST(A,B) - B must be sorted - Returns a vector of the
% locations of the elements of A occurring in B. If multiple
% instances occur, the first occurence is returned.
实际上引用了一个 ISMEMBERLAST 内置函数,但它似乎不存在(还没有?)。