0
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 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)

2
No it's not, in the previous question the values were summed in this question it's the maximum. So it's close but not identicaluser1543042
I think this shows a lack of research.user1543042
You are right, doing the first projects in matlab needs much effort and research but I think the elegant and versatile answer you pose in this forum is much more richer than matlab help pages (e.g. 'horzcat' use in the answer of "santhan" added to this answer). These features makes me brave to ask my question and get aware of experts' opinion. Meanwhile I try to ask better question. Thanks for spending time..hamideh

2 Answers

2
votes

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)].'
1
votes

Based upon your previous question and looking at the help file for accumarray, which has this exact example.

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

The only difference is the anonymous function.