Matlab:比较2个数组的索引,如果匹配,则为数组添加值

时间:2016-04-20 13:24:36

标签: arrays matlab

我有一个主数组,第一列有一个索引。我想通过将它们的索引(也是第一列)与主机进行比较,现在匹配一些数组,如果匹配,则将第2列的对应值添加到主数组。

我尝试过交叉,但无法让它发挥作用。

在master中我基本上将日期(数字不是日期格式)作为索引,我想要匹配的其他数组也在第一行中有日期,它应该在大多数情况下更短但它也可以数组具有主人没有的日期的情况。

master = [736182; 736183; 736186; 736187; 736188; 736189];

A = [736186  5
     736187  3
     736188  2];

B = [736187  -15
     736188  1
     736189  -12];

主人的期望结果

736182   
736183   
736186    5
736187    3   -15
736188    2     1
736189         -12

1 个答案:

答案 0 :(得分:0)

您需要使用second output of ismember来确定AB中与master第1列中的索引相对应的行。然后,您可以使用此信息来获取AB的相关行,并根据需要使用它们。

%// Find the rows in A and B that correspond to the index value in master
[isInA, Aind] = ismember(master(:,1), A(:,1));  
[isInB, Bind] = ismember(master(:,1), B(:,1));

%// Get Column 2 of A and B that corresponds to the index in master 
%// and concatenate them to master. Any values in master that were not
%// found in A or B are replaced by NaN

new_master = [master, nan(size(master, 1), 2)];
new_master(isInA,2) = A(Aind(isInA), 2);
new_master(isInB,3) = B(Bind(isInB), 2);

%// MASTER  A     B
%// 736182  NaN   NaN
%// 736183  NaN   NaN
%// 736186    5   NaN
%// 736187    3   -15
%// 736188    2     1
%// 736189  NaN   -12

<强>更新

如果您需要在循环内填充new_master,可以在循环外部初始化new_master,然后在循环中填充它。

new_master = [master, nan(size(master, 1), 2)];

for k = 1:N
    A = %// Get new value for A
    B = %// Get new value for B

    %// Do comparisons
    [isInA, Aind] = ismember(master(:,1), A(:,1));
    [isInB, Bind] = ismember(master(:,1), B(:,1));

    new_master(isInA,2) = A(Aind(isInA), 2);
    new_master(isInB,3) = B(Bind(isInB), 2);
end