Sorting columns in classes
조회 수: 4 (최근 30일)
이전 댓글 표시
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
채택된 답변
Guillaume
2018년 7월 5일
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
Guillaume
2018년 7월 6일
Undefined function 'compose'
That's because you're on a version of matlab earlier than R2016b. It's always a good idea to say that you're on an old version in your question (or fill the Release field next to the question).
On old versions, you can replace compose by the undocumented sprintfc:
groupnames = sprinfc('%f-%f', [edges(1:end-1); edges(2:end)]');
or use a loop:
groupnames = arrayfun(@(s, e) sprintf('%f-%f', s, e), edges(1:end-1), edges(2:end), 'UniformOutput', false);
or not bother with the groupnames (which is only for pretty display of the groups) and do:
T.rowlabels = group;
instead.
추가 답변 (1개)
Matt J
2018년 7월 4일
편집: Matt J
2018년 7월 4일
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
Guillaume
2018년 7월 5일
Matt made a mistake.
T(:,2:3).VariableNames
should be
T.Properties.VariableNames(2:3)
참고 항목
카테고리
Help Center 및 File Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!