排行" ismember"没有for-loop

时间:2017-09-13 14:41:08

标签: matlab for-loop

我正在尝试按顺序执行" ismember"在MATLAB中,为了找出SetInput的每个元素的位置。 到目前为止,这是我的工作。

function lia = ismemberrow(Input, Set)
    lia = false(size(Input)); % Pre-assign the output lia
    for J = 1 : size(Input,1)
        % The J-th row of "lia" is the list of locations of the
        % elements of Input(J,:) in Set
        lia(J,:) = find(ismember(Set, Input(J,:)));
    end
end

例如,如果变量InputSet定义如下

Input = [1 4; 
         4 2; 
         4 3; 
         2 4; 
         1 2; 
         3 2];
Set = [3 2 4 1];

lia的输出lia = ismemberrow(Input,Set)将为:

lia = [4 3; 
       3 2; 
       3 1; 
       2 3; 
       4 2; 
       1 2];

到目前为止,我的函数工作正常,但是在我的项目中多次调用此函数,所以我想如果我可以减少for循环以便花费更少的时间。我可以就此发表意见吗?

3 个答案:

答案 0 :(得分:4)

单次调用ismember(无需循环)将在第二个输出参数中为您提供所需内容:

>> [~, lia] = ismember(Input, Set)

lia =

     4     3
     3     2
     3     1
     2     3
     4     2
     1     2

答案 1 :(得分:1)

如果您的输入是正整数,则只需使用索引

m(Set)=1:numel(Set);
result = m(Input)

如果输入范围很大,您可以使用稀疏矩阵:

s = sparse(Set,1,1:numel(Set));
result = s(Input)

结果:

   4   3
   3   2
   3   1
   2   3
   4   2
   1   2

答案 2 :(得分:1)

我和@gnovice's answer中的ismember一样。但是这里有一些替代品,只是为了它的乐趣。

  1. 如果Input中的值保证在Set中:

    [ind, ~] = find(bsxfun(@eq, Set(:), Input(:).'));
    result = reshape(ind, size(Input));
    
  2. 如果不能保证:

    [ind, val] = max(bsxfun(@eq, Set(:), permute(Input, [3 1 2])));
    result = permute(ind.*val, [2 3 1]);