2
votes

I am working with nx2 matrices in Matlab, and what I'm trying to do is fairly simple in principle. I randomly generate a square matrix, I run it through a series of functions and I get an mx2 matrix. I use the unique function on the rows to get rid of repeated rows and I end up with an nx2 matrix. What I'm having trouble doing is further reducing this matrix so that for all entries in the first column that have the exact same entry, only keep the row with the highest number on the second column.

I was using a loop to check the ith and (i+1)th entries of the first column and store the rows with the highest value in the second column, but I am trying to avoid for-loops as much as possible.

If anyone has an idea or suggestion please let me know!

Example:

        0  0                            0  0     
        0  1                            0  1             0  3          
 A=     0  3   ---> unique(A, 'rows') = 0  3  --WANT-->  1  1
        1  0                            1  0             2  4
        1  0                            1  1
        0  0                            2  1
        2  1                            2  4    
        1  1                                                    
        2  4                                        
2

2 Answers

2
votes

What you are looking for is:

[u,~,n] = unique(A(:,1));
B = [u, accumarray(n, A(:,2), [], @max)];
1
votes

I don't exactly understand your problem description, but it sounds like sortrows() may be of some help to you.