【问题标题】:Pairs of positions of equal elements of a matrix in MatlabMatlab中矩阵的相等元素的位置对
【发布时间】:2018-08-03 10:34:50
【问题描述】:

我在 Matlab 中有一个行向量A,其中可能包含重复的整数。我希望您帮助构建一个矩阵B,报告A 的所有可能的相等元素的位置对。正如下面的 cmets 所述,困难的部分是我不想在B“冗余”对中列出。

让我用一个例子更好地解释一下。

clear
A=[100 101 100 100 101 200];

我们可以看到

%A(1)=A(3)=A(4);
%A(2)=A(5);

因此,

 B=[1 3; 1 4; 2 5];

或者,等价的,

B=[1 3; 3 4; 2 5];

B=[1 4; 3 4; 2 5];

我对上面报告的三个向量B 中的任何一个都无动于衷。

注意我不想要

B=[1 3; 1 4; 3 4; 2 5];

因为(1,3), (1,4), (3,4) 中的一对是冗余的,即如果A(1)=A(3)A(1)=A(4),那么A(4)=A(3) 和其他组合类似。

我尝试使用unique,但unique 提供的输出似乎都没有给出所需的矩阵。有什么帮助吗?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    如果你不喜欢使用循环,正如@Wolfie 的answer 所建议的,你可以使用accumarray

    [~,~,idx]=unique(A,'stable');
    B = accumarray                                      ...
        (                                               ...
            idx(:),                                     ...
            (1:numel(A)).',                             ...
            [],                                         ...
            @(x)                                        ...
            {                                           ...
                [repmat(x(1),numel(x)-1,1) x(2:end,1)]  ...
            }                                           ...
        );
    result = vertcat(B{:})
    

    【讨论】:

      【解决方案2】:

      这里需要考虑的部分是冗余配对。删除冗余配对的最简单方法是为每个值设置一个键索引,并将所有匹配值链接到该索引。

      在您的示例中,这意味着使用以下关系

      % A(1) = A(3)
      % A(1) = A(4)
      % A(2) = A(5)
      

      每个值的第一个等价都暗示了这一点,例如,A(3)=A(4)

      为此,我们可以使用unique 的最后一个索引输出,然后循环设置这个等价索引。看下面的代码,用cmets来理解:

      % A is the input row vector
      A=[100 101 100 100 101 200];
      % Get the 'unique' indexing output
      [~, ~, juA] = unique(A);
      % Set up output as cell so we don't have to worry about how many rows each
      % equivalence will take up.
      B = cell( max(juA), 1 );
      % Loop through all of the unique indices
      for ii = 1:max(juA)    
          % Get indices where the value is equal to the current value   
          k = find( juA == ii );  
          % Output for this value is [1 x; 1 y; 1 z; ...] where x/y/z are indices
          % of equivalent values
          B{ii} = [repmat(k(1), numel(k)-1, 1), k(2:end)]; 
      end
      % Concatenate cell array B to be a 2 column numeric array
      B = vertcat(B{:});
      

      输出:

      >> B = [1 3; 1 4; 2 5]
      

      【讨论】:

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