合并已排序的对

zeg*_*jan 1 matlab numpy octave

我有两个(或更多,但如果解决了两个,它解决了任何数字)2×N矩阵,它代表具有x(第一行)和y(第二行)坐标的点.这些点始终按递增的x坐标排序.我想要做的是我想将这两个矩阵合并为一个3乘N矩阵,这样如果两个点(每个矩阵一个)具有相同的x坐标,它们将在新矩阵中形成一列,第一个row是x坐标,第二和第三行是两个y坐标.但是,如果一个矩阵中的某个点的x坐标与第二个矩阵中的所有其他点不同,我仍然希望放置完整的3个元素列,使得x坐标仍然排序,并且缺少的值来自另一个矩阵由具有较低x坐标的最近值(如果没有则为NaN)替换.

最好通过例子来解释.

第一个矩阵:

1  3  5  7  % x coordinate
1  2  3  4  % y coordinate
Run Code Online (Sandbox Code Playgroud)

第二个矩阵:

2  3  4  7  8  % x coordinate
5  6  7  8  9  % y coordinate
Run Code Online (Sandbox Code Playgroud)

期望的结果:

1    2  3  4  5  7  8  % x coordinate
1    1  2  2  3  4  4  % y coordinate from first matrix
NaN  5  6  7  7  8  9  % y coordinate from second matrix
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何在matlab/octave和numpy中有效地完成它?(实际上,因为我总是可以"手动"使用循环,但这似乎不正确.)

Nic*_*son 5

您可以使用interp1'previous'策略的关键字(您也可以选择'nearest'是否不关心它是否更大或更小)以及'extrap'允许外推.

定义矩阵

a=[...
1  3  5  7;... 
1  2  3  4];

b=[...
2  3  4  7  8;...
5  6  7  8  9];
Run Code Online (Sandbox Code Playgroud)

然后找到插值点

x = unique([a(1,:),b(1,:)]);
Run Code Online (Sandbox Code Playgroud)

并插入

[x ; interp1(a(1,:),a(2,:),x,'previous','extrap') ; interp1(b(1,:),b(2,:),x,'previous','extrap') ]
Run Code Online (Sandbox Code Playgroud)

时间结果:

我测试了算法

n = 1e6;
a = cumsum(randi(3,2,n),2);
b = cumsum(randi(2,2,n),2);
Run Code Online (Sandbox Code Playgroud)

得到了:

  • 沃尔夫:1.7473秒
  • Flawr:0.4927 s
  • 我的:0.2757秒