【问题标题】:Row-wise "ismember" without for-loop没有for循环的逐行“ismember”
【发布时间】:2017-09-13 14:41:07
【问题描述】:

我正在尝试在 MATLAB 中执行逐行“ismember”,以便找出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 = ismemberrow(Input,Set) 的输出 lia 将是:

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

到目前为止,我的函数工作正常,但是这个函数在我的项目中被调用了很多次,所以我在想如果我可以减少 for 循环以减少它花费的时间。我可以对此发表一些意见吗?

【问题讨论】:

    标签: matlab for-loop


    【解决方案1】:

    ismember 的一次调用(无需循环)将在第二个输出参数中为您提供您想要的:

    >> [~, lia] = ismember(Input, Set)
    
    lia =
    
         4     3
         3     2
         3     1
         2     3
         4     2
         1     2
    

    【讨论】:

      【解决方案2】:

      我会选择ismember,就像@gnovice's answer一样。但这里有一些替代方案,只是为了好玩。

      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]);
        

      【讨论】:

        【解决方案3】:

        如果您的输入是正整数,您可以简单地使用索引

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多