Search code examples
matlabmatrixmaxcell-array

Merge two matrix and find the maximum of its attributes


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 and b which have the same row value get the maximum value in new matrix. i.e.

a = 1     2     3
    8     2     5 

b = 1     2     5     7
    2     4     6     1 

Desired output

c =  1     2     3     5     7
     8     4     5     6     1

Any help is welcomed,please.( the case for accumulation is asked here)


Solution

  • Accumarray accepts functions both anonymous as well as built-in functions. It uses sum function as default. But you could change this to any in-built or anonymous functions like this:

    In this case you could use max function.

    in = horzcat(a,b).';
    [uVal,~,idx] = unique(in(:,1));
    
    out = [uVal,accumarray(idx,in(:,2),[],@max)].'