MATLAB Answers

# Sorting columns in classes

10 views (last 30 days)
giometar on 4 Jul 2018
Edited: Matt J on 11 Jul 2018
Hello I have table
T =
Distance ddfi ddla
_________ ________ ______
0.25445 0.032528 330.13
0.11412 0.023379 330.85
0.10778 0.022379 330.9
0.12522 0.022749 331.04
0.11136 0.018143 331.56
0.1489 0.02429 331.24
0.2754 0.03361 330.62
0.13454 0.017196 331.82
0.1302 0.018947 331.64
0.33098 0.037232 330.54
0.15657 0.023177 331.48
0.2157 0.029463 331.39
0.15954 0.019613 331.9
0.17042 0.021007 331.92
0.1996 0.02608 331.59
0.18505 0.019299 332.16
0.20692 0.024783 331.71
0.21569 0.026374 331.68
0.19809 0.021438 332.14
0.26943 0.030838 331.39
So I need to sort this table by first column, but in a specific interval so to get classes. For example: I sort table by first row using interval 0.05 to get classes and the sum all data in same class from second column and third column. This is done in excel using pivot table and grouping:
Row Labels Sum of ddfi Sum of ddla
0.10778-0.15778 0.170 2650.530
0.15778-0.20778 0.067 995.410
0.20778-0.25778 0.062 661.520
0.25778-0.30778 0.034 330.620
0.30778-0.35778 0.037 330.540
Grand Total 0.369793 4968.62
Thanks for help
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Guillaume on 5 Jul 2018
A simpler option than splitapply is to use varfun:
edges = min(T.Distance):0.05:max(T.Distance)+0.05;
group = discretize(T.Distance, edges);
groupnames = compose('%f-%f', edges(1:end-1)', edges(2:end)');
T.rowlabels = groupnames(group);
newtable = varfun(@sum, T, 'GroupingVariables', 'rowlabels', 'InputVariables', {'ddfi', 'ddla'})
##### 3 CommentsShowHide 2 older comments
giometar on 11 Jul 2018
Sorry. My mistake. It works fine...

Sign in to comment.

### More Answers (1)

Matt J on 4 Jul 2018
Edited: Matt J on 4 Jul 2018
You don't need sorting to do that. Just use discretize()
G=discretize(T{:,1},edges);
then use splitapply on each of the variables
for i=[3,2]
result(:,i-1)=splitapply(@sum,T{:,i},G);
end
newTable=array2table(result,'VariableNames',T(:,2:3).VariableNames);
##### 3 CommentsShowHide 2 older comments
giometar on 6 Jul 2018
With that code
Table=[D, ddfi, ddla];
T = array2table(Table,...
'VariableNames',{'Distance','ddfi','ddla'});
G=discretize(T{:,1},[0 0.05]);
for i=[3,2]
result(:,i-1)=splitapply(@sum,T{:,i},G);
end
newTable=array2table(result,...
'VariableNames',T.Properties.VariableNames(2:3));
I get empty 0x2 newTable

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!