0

I have this struct:

s = 

p_10_50_10_70: 0.1176
p_10_50_15_10: 0.9235
p_10_50_15_70: 0.2456
 p_10_50_base: 0.0100
p_10_70_15_10: 0.0895
p_10_70_15_70: 0.0053
 p_10_70_base: 6.3711e-06
p_15_10_15_70: 0.1892
 p_15_10_base: 0.0047
 p_15_70_base: 0.3377
 p_5_30_10_50: 0.0864
 p_5_30_10_70: 0.0014
 p_5_30_15_10: 0.0654
 p_5_30_15_70: 0.6165
  p_5_30_5_70: 0.0052
  p_5_30_8_30: 0.8106
  p_5_30_8_70: 0.0378
  p_5_30_base: 0.6113
 p_5_70_10_50: 0.2215
 p_5_70_10_70: 0.7448
 p_5_70_15_10: 0.2444
 p_5_70_15_70: 0.0221
  p_5_70_8_30: 0.0024
  p_5_70_8_70: 0.5382
  p_5_70_base: 2.1956e-04
 p_8_30_10_50: 0.0699
 p_8_30_10_70: 8.1918e-04
 p_8_30_15_10: 0.0599
 p_8_30_15_70: 0.7169
  p_8_30_8_70: 0.0218
  p_8_30_base: 0.9146
 p_8_70_10_50: 0.5467
 p_8_70_10_70: 0.3395
 p_8_70_15_10: 0.5552
 p_8_70_15_70: 0.0775
  p_8_70_base: 0.0015

`

I want to sort it by values, and I realise this may not be the best datatype to do this kind of sorting. I am using Matlab R2012b which does not have the table datatype, how can I end up with an data structure which contains both key names and values, ordered by the numeric value?

Going forward what is the best datatype for a key value pair array such as this, if I want to sort by value?

Thanks!

Suever
  • 64,497
  • 14
  • 82
  • 101
Mazatec
  • 11,481
  • 23
  • 72
  • 108
  • try nestedSortStruct by Jake Hughey https://www.mathworks.com/matlabcentral/fileexchange/28573-nestedsortstruct – Eric Wang Mar 12 '19 at 06:27

1 Answers1

3

Looks like this does it:

[~, idxs] = sort(cell2mat(struct2cell(s)));
s = orderfields(s, idxs);

Edit: As for your final question, yeah I'm not sure there are great options. The only thing better than what you've got might be a class, with a cell array of strings and a vector of corresponding values, and setter/getter functions to make access efficient.

Matt Phillips
  • 9,465
  • 8
  • 44
  • 75
  • thanks that's awesome, what is this bit `[~, idxs] = ` about? – Mazatec Jun 24 '14 at 21:09
  • 2
    @Ash Oh that is 'modern' Matlab notation for a dummy variable. Replace the `~` with `dummy` or something else if your version of Matlab doesn't support it. – Matt Phillips Jun 24 '14 at 21:11