Sahar Rabinoviz
Sahar Rabinoviz

Reputation: 1979

Sorting on Structs In Matlab

In Matlab I have an array of structs("sort_on_this", ...)

How do I sort the array on the on sort_on_this?

Example of what I am trying to do,

list_to_sort = [struct('a', 4), struct('a', 0), struct('a', 3), struct('a', 1)]
sort(list_to_sort on 'a') = 
      [struct('a', 0), struct('a', 1), struct('a', 3), struct('a', 4)] 

edit: question is not duplicate, because the the other question has arrays within the struct that needed to be sorted whereas this is an array of structs that needs to be sorted.

Upvotes: 0

Views: 590

Answers (1)

beaker
beaker

Reputation: 16791

As you've probably figured out, the normal sort doesn't work on structs. You can, however, build an array of the values that you then sort and use the new ordering to reorder the original struct array.

Starting with our struct array:

list_to_sort = [struct('a', 4), struct('a', 0), struct('a', 3), struct('a', 1)]

Get the struct field values into an array:

a_values = [list_to_sort.a]

a_values =
   4   0   3   1

Now, sort a_values, keeping the second return value from sort which gives us the original indices of the sorted values.

[~,inds] = sort(a_values)
inds =    
   2   4   3   1

Finally, use these indices to reorder your struct:

sorted_list = list_to_sort(inds)

>> disp([sorted_list.a])
   0   1   3   4

Upvotes: 4

Related Questions