Sort a cell array based on average of one cell column/row, then sort the structure
2 次查看(过去 30 天)
显示 更早的评论
Hi, I have a cell array that contains a number of n by 2 matrices. I want to do the following:
- determine the averge value of the columns in each matrix.
- sort the cell array based on the average values of column 1 (or column 2, for another analysis)
- 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!
0 个评论
采纳的回答
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.
更多回答(1 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!