pyigal
pyigal

Reputation: 389

merging two matrices in matlab

I'm having two sets of vectors as follows:

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

and I would like to merge them to get this result:

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

Is there any built-in function in Matlab that does it?

Upvotes: 0

Views: 51

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112759

This can be done as follows:

  1. The first ouput of unique gives the desired a. The third output gives positive integer labels, u, that identify the groups.
  2. To sum the elements of each group, call accumarray with u as first input.

Code:

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

Upvotes: 3

Related Questions