Venkat kamal
Venkat kamal

Reputation: 279

Keeping rows corresponding to identical elements in columns together in matlab

I have a matrix as shown below. The first column contains identity of objects and the second and third column corresponds to there detection times. What i want to do is to keep all the elements corresponds to the identical elements in the first column together.

eg:

a = [51, 1.5, 3.8; 
     52, 1.8, 9.6; 
     53, 2.1, 8.8; 
     51, 3.5, 9.9; 
     54, 8.5, 10.23;
     51, 1.5, 3.8 ];

Is there a way to do this rather than using for loops and conditions? Any help will be appreciated.

Upvotes: 0

Views: 40

Answers (1)

Jack G
Jack G

Reputation: 96

Do you want to group all the 'first column element' together? e.g:

    a = [51, 1.5, 3.8;
         51, 3.5, 9.9; 
         51, 1.5, 3.8;
         52, 1.8, 9.6; 
         53, 2.1, 8.8; 
         54, 8.5, 10.23];

You could sort the matrix according to the first column:

[~, a_sorted_idx] = sort(a(:,1));
a_sorted = a(a_sorted_idx,:);

Upvotes: 1

Related Questions