MATLAB: Sort a cell array based on average of one cell column/row, then sort the structure

cell srraysort

Hi, I have a cell array that contains a number of n by 2 matrices. I want to do the following:
  1. determine the averge value of the columns in each matrix.
  2. sort the cell array based on the average values of column 1 (or column 2, for another analysis)
  3. re-arrange other fields in the structure based on this new order
For example say field 1 is a cell array (1×5 cells) contains matrices: 8×2, 6×2, 9×2, 7×2, 7×2; I want to sort this, then use the order to sort field 2, which contains 5 vectors (a 5×20 matrix), and field 3, which is another cell array 1×5 cells. I hope this makes sense.
Can anyone help thank you very much!

Best Answer

See this example
rng(0); % repeatability
A = {rand(8,2), rand(10,2), rand(6,2)}; % example data
A_avg = cellfun(@(x) mean(x(:,1)), A); % get average of first columns
[~,idx] = sort(A_avg);
A_sorted = A(idx);
This arrange the cell array A, using the average of first column, in an ascending order.