在matlab中合并两个矩阵

时间:2017-05-29 08:47:22

标签: matlab merge

我有两组载体如下:

a1 = [0,1,2,3,4]; % the unique elements 
b1=[12,35,60,20,7]; % the number of repitition of each element
a2 = [0,1,6]; % the unique elements 
b2=[15,40,2]; % the number of repitition of each element

我希望将它们合并以获得此结果:

a=[0,1,2,3,4,6];
b=[27,75,60,20,7,2];

Matlab中是否有内置函数可以做到?

1 个答案:

答案 0 :(得分:3)

这可以按如下方式完成:

  1. unique的第一个输出提供了所需的a。第三个输出给出正整数标签u,用于标识组。
  2. 要对每个组的元素求和,请以u作为第一个输入来调用accumarray
  3. 代码:

    [a, ~, u] = unique([a1(:); a2(:)]);
    a = a(:).';
    b = accumarray(u, [b1(:); b2(:)]).';
    
相关问题