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

3 ビュー (過去 30 日間)
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!

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 4 月 15 日
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.
  2 件のコメント
alicia che
alicia che 2020 年 4 月 17 日
Thank you! This worked great for me and so simple!
Ameer Hamza
Ameer Hamza 2020 年 4 月 17 日
I am glad to be of help.

サインインしてコメントする。

その他の回答 (1 件)

Peng Li
Peng Li 2020 年 4 月 15 日
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, :);
else
y = x(indSort);
end
end

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by