将基于相应索引的矩阵行中的单元格值添加到另一个矩阵行中

时间:2019-03-21 14:04:45

标签: arrays matlab indexing

我有两个数组AB

数组A的第1列包含样本的索引号;矩阵A的其他列包含每个样本的其他属性(在数组B中,每行的前两个单元格包含一个属性和样本的索引号)。

数组B的第2、4和6列包含矩阵A中包含的样本的索引号。

我正在尝试将相应的样本属性插入数组A的第4列中(基于数组AB的相应索引号)到新的第3、6和9列中矩阵B;具有如下所示的矩阵C

A = [1,3.43,2.34,5.43,3.22;2,8.32,6.34,7.34,2.34;3,3.67,8.34,8.23,1.34;4,2.67;6.89,4.99,8.65;5,1.33,5.42,2.53,6.13]     
B = [0.12,2,0.15,1,0.65,3;0.33,5,0.62,4,0.55,1;0.91,1,0.77,2,0.66,5]    
C = [0.12,2,7.34,0.15,1,5.43,0.65,3,1.34;0.33,5,2.53,0.62,4,4.99,0.55,1,5.43;0.91,1,5.43,0.77,2,7.34,0.66,5,2.53]

我尝试了以下代码,但出现错误:

for i = 1:3
    f = ismember(A(:,1(i)), B(:,2), 'rows');
    k = find(f);
    f = A(f,4);
    C = [C,f(i)]
end

1 个答案:

答案 0 :(得分:0)

首先,您在A矩阵中有一个typo-不同大小的行。也许你是说:

A = [1,3.43,2.34,5.43,3.22;
    2,8.32,6.34,7.34,2.34;
    3,3.67,8.34,8.23,1.34;
    4,2.67,6.89,4.99,8.65;
    5,1.33,5.42,2.53,6.13];

B = [ 0.12,2,0.15,1,0.65,3;
    0.33,5,0.62,4,0.55,1;
    0.91,1,0.77,2,0.66,5];

因此,如果您运行代码,则数字会很多,但顺序却不好。您应该尝试:

Z = [0;0;0];
C = [[B(:,1:2) Z B(:,3:4) Z B(:,5:6)]]; %Generating satic part
for j = 1:3 %generating dynamic part in loop
    for i = 1:3
        n = A(find(ismember(A(:,(1)), B(i,j*2), 'rows')),4);
        C(i,j*3) = n;
    end
end

输出为:

C =

    0.1200    2.0000    7.3400    0.1500    1.0000    5.4300    0.6500    3.0000    8.2300
    0.3300    5.0000    2.5300    0.6200    4.0000    4.9900    0.5500    1.0000    5.4300
    0.9100    1.0000    5.4300    0.7700    2.0000    7.3400    0.6600    5.0000    2.5300