hamideh
hamideh

Reputation: 225

merge two matrix and its attributes in matlab

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.

Upvotes: 1

Views: 77

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

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,:)]))];

Upvotes: 3

Related Questions