1
votes

I've two matrix a and b and I'd like to combine the rows in a way that in the first row I got no duplicate value and in the second value, columns in a & b which have the same row value get added together in new matrix. i.e.

a =
 1     2     3
 8     2     5

b =
 1     2     5     7
 2     4     6     1

Desired outputc =

 1     2     3     5     7
10     6     5     6     1

Any help is welcomed,please.

1
What do you mean by combine/merge? What happens if the input matrices have different rows/columns size?NKN
as in the example, columns are of arbitrary size. the first row is as the key and I'd like to have non-duplicate value of this row (e.g. by union(a(1,:)),b(1,:)). for the other rows, whatever they have equal first row value, these get added together (e.g. 8 from a and 2 from b are added and result is 10 for the value beneath 1 in the output matrix).hamideh

1 Answers

3
votes

For two-row matrices

You want to add second-row values corresponding to the same first-row value. This is a typical use of unique and accumarray:

[ii, ~, kk] = unique([a(1,:) b(1,:)]);
result = [ ii; accumarray(kk(:), [a(2,:) b(2,:)].').'];

General case

If you need to accumulate columns with an arbitrary number of columns (based on the first-row value), you can use sparse as follows:

[ii, ~, kk] = unique([a(1,:) b(1,:)]);
r = repmat((1:size(a,1)-1).', 1, numel(kk));
c = repmat(kk.', size(a,1)-1, 1);
result = [ii; full(sparse(r,c,[a(2:end,:) b(2:end,:)]))];