필터 지우기
필터 지우기

Avoiding for loop: Ordering and assigning order of Group data

조회 수: 1 (최근 30일)
Pete sherer
Pete sherer 2023년 8월 23일
댓글: Pete sherer 2023년 8월 23일
Hi
I have this data, and would like to order the loss within each group and assign the ordering index to each element.
tdata = table(["US";"US";"US";"UK";"UK";"TW";"TW";"TW";"TW"], [1;1;5;1.20000000000000;3;4;5;1;2],'VariableNames',{'name','Loss'});
name Loss
"US" 1
"US" 1
"US" 5
"UK" 1.20000000000000
"UK" 3
"TW" 4
"TW" 5
"TW" 1
"TW" 2
[ uniqGrp,~,JGrp]= unique( tdata( :,{'name'}));
tAll = table;
for runi= 1: height( uniqGrp)
tt = tdata( JGrp== runi, :);
tt = sortrows( tt, {'Loss'});
tt.idx = [1:height(tt)]';
tAll = [tAll; tt];
end
so final data tAll looks like this
name Loss idx
"TW" 1 1
"TW" 2 2
"TW" 4 3
"TW" 5 4
"UK" 1.20000000000000 1
"UK" 3 2
"US" 1 1
"US" 1 2
"US" 5 3

채택된 답변

Matt J
Matt J 2023년 8월 23일
편집: Matt J 2023년 8월 23일
tdata = table(["US";"US";"US";"UK";"UK";"TW";"TW";"TW";"TW"], [1;1;5;1.20000000000000;3;4;5;1;2],'VariableNames',{'name','Loss'});
out=varfun(@gfunc,tdata,'Group','name','Input','Loss');
out=table(out.name,out{:,3}(:,1), out{:,3}(:,2), 'Var',["name","Loss","idx"])
out = 9×3 table
name Loss idx ____ ____ ___ "TW" 1 1 "TW" 2 2 "TW" 4 3 "TW" 5 4 "UK" 1.2 1 "UK" 3 2 "US" 1 1 "US" 1 2 "US" 5 3
function out=gfunc(y)
x=sort(y);
out=[x,(1:numel(x))'];
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by