Sort a cell array based on average of one cell column/row, then sort the structure
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
alicia che
el 15 de Abr. de 2020
Comentada: Ameer Hamza
el 17 de Abr. de 2020
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 comentarios
Respuesta aceptada
Ameer Hamza
el 15 de Abr. de 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.
2 comentarios
Más respuestas (1)
Peng Li
el 15 de Abr. de 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, :);
else
y = x(indSort);
end
end
0 comentarios
Ver también
Categorías
Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!