Sorting Array Structures in Matlab

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

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

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

+4
source share
3 answers

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

 B = nestedSortStruct(A, 'Return'); 
+3
source

As I mentioned above, you do not know. I think you are misleading the structure and structure of arrays. This post may help.

So, here is an example to show what I think you wanted to do.

First I create an array of structure 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 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, you can sort this array of the structure by the "return" field (each structure has a corresponding scalar value):

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

As a result, the array is sorted by "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 
+4
source

A solution with built-in functions can only 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.

+1
source

Source: https://habr.com/ru/post/1501055/


All Articles