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

4 Ansichten (letzte 30 Tage)
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 (1x5 cells) contains matrices: 8x2, 6x2, 9x2, 7x2, 7x2; I want to sort this, then use the order to sort field 2, which contains 5 vectors (a 5x20 matrix), and field 3, which is another cell array 1x5 cells. I hope this makes sense.
Can anyone help thank you very much!

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 15 Apr. 2020
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.

Weitere Antworten (1)

Peng Li
Peng Li am 15 Apr. 2020
I thought I answered this question... anyway, this is less clearer than the other one you asked. See example below
% generated a 1 by 5 cell, each with a n*2 random matrix.
% n generated randomly within 1 and 20
ind = 1:5;
testCell = arrayfun(@(x) rand(randi(20), 2), ind, 'UniformOutput', 0);
% make it a field of a struct
testStruct.field1 = testCell;
% mean of each column within cell
meanInCell = cell2mat(cellfun(@mean, testCell, 'UniformOutput', 0)');
% sort by the mean of first column
[~, indSort] = sort(meanInCell(:, 1));
sortTestCell = testCell(indSort);
% other fields
testStruct.field2 = rand(5, 20);
% I guess you have the same n*2 within each cell of the field3
testStruct.field3 = arrayfun(@(x) rand(randi(20), 2), 1:5, 'UniformOutput', 0);
% sort all fields
sortTestStruct = structfun(@(x) mySort(x, indSort), testStruct, 'UniformOutput', 0);
function y = mySort(x, indSort)
if size(x, 1) > 1
y = x(indSort, :);
y = x(indSort);


Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by