【问题标题】:Matlab Merge Array with Offset Values具有偏移值的 Matlab 合并数组
【发布时间】:2015-07-17 07:00:46
【问题描述】:

假设我在 matlab 中有 2 个双精度数组,如何将它们与未知偏移量合并?

例如:

A = 
1 1
2 2
3 3
4 4
5 5

B = 
2 6
3 5
4 4
5 3
6 2

当我不知道 A 和 B 之间在第一列中的值的偏移/重叠时,有没有办法从这两个数组创建一个具有 3 列的单个数组,如下所示?

C =
1 1 NaN
2 2 6
3 3 5
4 4 4
5 5 3
6 NaN 2

有没有有效的方法来做到这一点?

我现在想出的解决方案是将 A 和 B 的第一列拼凑在一起,然后继续使用 for 循环进行迭代。

【问题讨论】:

    标签: matlab


    【解决方案1】:

    这似乎有效。我有点担心边缘情况,不是很多测试。

    A = [...
         1     1; ...
         2     2; ...
         3     3; ...
         4     4; ...
         5     5];
    B = [...
         2     6; ...
         3     5; ...
         4     4; ...
         5     3; ...
         6     2];
    
    C1 = union(A(:,1), B(:,1));
    
    C2 = nan(size(C1));
    [~, ixsA] = ismember(A(:,1), C1);
    C2(ixsA) = A(:,2);
    
    C3 = nan(size(C1));
    [~, ixsB] = ismember(B(:,1), C1);
    C3(ixsB) = B(:,2);
    
    C = [C1 C2 C3];
    

    【讨论】:

      【解决方案2】:

      union 的组合可以获取唯一元素,然后ismember 可以找到相应的位置。

      请注意,这将允许 AB 具有任意数量的 2 或更多列。

      A = [1 1;2 2;3 3;4 4;5 5];
      B = [2 6;3 5;4 4;5 3;6 2];
      
      %Get the elements from the first columns of A and B
      C = union(A(:,1), B(:, 1));
      %Prepopulate C to the correct size with NaN's
      C = [C, nan(size(C,1), size(A,2) + size(B,2) - 2)];
      
      %Find the rows of C where column 1 of A ended up
      [~, i] = ismember(A(:,1), C(:,1));
      %Stick the rest of A in those rows in the first set of free columns
      C(i, 2:size(A,2)) = A(:,2:end);
      
      %Now do the same with B in the second set of free columns
      [~, i] = ismember(B(:,1), C(:,1));
      C(i, size(A,2) + 1:end) = B(:,2:end);
      
      C
      
      C =
      
           1     1   NaN
           2     2     6
           3     3     5
           4     4     4
           5     5     3
           6   NaN     2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多