Kiran
Kiran

Reputation: 8528

Sort a structure of arrays in Matlab

I have a structure of arrays StockInfo in Matlab. The fields of the structure StockInfo are as follows:

StockInfo = 

      Name: {10x1 cell}
    Values: [10x6 double]
    Return: [10x1 double]

I need to sort StockInfo based on the field Return, so that each array in the struct is sorted accordingly. Any idea how to do it?

Upvotes: 4

Views: 6939

Answers (3)

Amro
Amro

Reputation: 124563

As I mentioned in the comment above, you question is unclear. I think you are confusing structures and structure arrays. This post might be of help.

That said, here is an example to show what I think you meant to do.

First I create a structure array with some random data:

% cell array of 10 names
names = arrayfun(@(k) randsample(['A':'Z' 'a':'z' '0':'9'],k), ...
    randi([5 10],[10 1]), 'UniformOutput',false);

% 10x6 matrix of values
values = rand(10,6);

% 10x1 vector of values
returns = randn(10,1);

% 10x1 structure array
StockInfo = struct('Name',names, 'Values',num2cell(values,2), ...
    'Return',num2cell(returns));

The created variable is a an array of structures:

>> StockInfo
StockInfo = 
10x1 struct array with fields:
    Name
    Values
    Return

where each element is a structure with the following fields:

>> StockInfo(1)
ans = 
      Name: 'Pr3N4LTEi'
    Values: [0.7342 0.1806 0.7458 0.8044 0.6838 0.1069]
    Return: -0.3818

Next can sort this struct array by the "return" field (each struct has a corresponding scalar value):

[~,ord] = sort([StockInfo.Return]);
StockInfo = StockInfo(ord);

The result is that the array is now sorted by the "return" values in ascending order:

>> [StockInfo.Return]
ans =
  Columns 1 through 8
   -0.3818    0.4289   -0.2991   -0.8999    0.6347    0.0675   -0.1871    0.2917
  Columns 9 through 10
    0.9877    0.3929

Upvotes: 4

texnic
texnic

Reputation: 4098

A solution with built-in functions only could be:

[~, ix] = sort(StockInfo.Return);
StockInfo = struct(...
    'Name', {StockInfo.Name{ix}}, ...
    'Values', StockInfo.Values(ix), ...
    'Return', StockInfo.Return(ix));

Replace ~ with any unused identifier if your Matlab is older and does not support unused output arguments.

Upvotes: 1

marsei
marsei

Reputation: 7751

You can sort structure arrays based on fields with the FileExchange function nestedSortStruct (link).

B = nestedSortStruct(A, 'Return');

Upvotes: 3

Related Questions