How do I sort an array according to the first column?
7 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
lil brain
le 28 Juil 2022
Commenté : lil brain
le 28 Juil 2022
Hi,
I have a cell array which I would like to sort according to the first column. But when I try using
high_emp_sort = sort(high_empathy_ID_factors);
% or
high_emp_sort = sortrows(high_empathy_ID_factors);
... then I only get back errors. Could somebody kindly help?
Jeff
0 commentaires
Réponse acceptée
Image Analyst
le 28 Juil 2022
Modifié(e) : Image Analyst
le 28 Juil 2022
Did you mean by the first numerical column? Like this:
%====================================================================================
% Read in data.
storedStructure = load('high_empathy_ID_factors.mat');
ca = storedStructure.high_empathy_ID_factors;
data = cell2mat(ca(:, 2:end))
fprintf('Read %d rows by %d columns into data.\n', size(data, 1), size(data, 2));
%====================================================================================
% Sort by column 1.
fprintf('Sorting data by column 1.\n');
[sortedData, sortOrder] = sortrows(data, 1);
%====================================================================================
% Sort original cell array also.
fprintf('Sorting original cell array in the same order of rows.\n');
ca = ca(sortOrder, :)
Or did you really mean by the long alphanumeric hexadecimal strings in the first column? Like this:
%====================================================================================
% Read in data.
storedStructure = load('high_empathy_ID_factors.mat')
ca = storedStructure.high_empathy_ID_factors;
data = cell2mat(ca(:, 2:end))
[rows, columns] = size(data);
fprintf('Read %d rows by %d columns into data.\n', rows, columns);
%====================================================================================
% Convert hex numbers in column 1 to decimal
for row = 1 : rows
c = char(ca{row, 1});
% Can only convert the first 16 digits.
numbers(row) = hex2dec(c(1:16));
end
%====================================================================================
% Sort by column 1.
fprintf('Sorting data by column 1.\n');
[sortedData, sortOrder] = sort(numbers)
%====================================================================================
% Sort original cell array also.
fprintf('Sorting original cell array in the same order of rows.\n');
ca = ca(sortOrder, :)
3 commentaires
Image Analyst
le 28 Juil 2022
Modifié(e) : Image Analyst
le 28 Juil 2022
See my edited answer above.
Or maybe read them into tables with readtable(), and use one of the members of the "join" functions to combine the tables.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Data Type Conversion dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!