0

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.

Community
  • 1
  • 1
Sahar Rabinoviz
  • 1,939
  • 2
  • 17
  • 28
  • Sort with respect to what? Contents? Name? Size? – Adriaan Nov 10 '15 at 16:10
  • @Adriaan I want to sort with respect to the variable sort_on_this which is a number – Sahar Rabinoviz Nov 10 '15 at 19:47
  • @rayryeng I tried using the solution that you marked this [question a duplicate](http://stackoverflow.com/a/29055553/3024116) to, but it has lists inside the struct not a list of structs. So this question is different. – Sahar Rabinoviz Nov 10 '15 at 19:56
  • That wasn't clear in your original post. Now that you made an edit, it's certainly different. Please make an effort to give as much detail as possible in future questions you post. – rayryeng Nov 10 '15 at 20:15
  • 1
    @rayryeng my apology, I was merely in a hurry this morning next time I will simple not post the question until enough detail is provided. Could you please unmark it as a duplicate? – Sahar Rabinoviz Nov 10 '15 at 20:17
  • @DisplayName101 already done. – rayryeng Nov 10 '15 at 20:19
  • 2
    There are no arrays in the struct, you are miss-understanding the struct constructor. `list_to_sort = [struct('a', 4), struct('a', 0), struct('a', 3), struct('a', 1)]` and `list_to_sort = struct('a', {4,0,3,1})` both produce the same. – Daniel Nov 10 '15 at 21:07

1 Answers1

4

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
beaker
  • 16,331
  • 3
  • 32
  • 49