How to do inline function with unique instead of using for loop

조회 수: 4 (최근 30일)
Pete sherer
Pete sherer 2025년 5월 17일
편집: Matt J 2025년 5월 18일
tdata = table([1 1 1 3 4 4 4 4]', ["eq","fr","wt","fl","eq","fr","fl","tr"]', [24 55 10 5 3 5 7 9 ]', int64([ 5 2 7 1 50 10 5 5 ]'),...
'VariableNames',["EBID","Peril","Loss","Trial"]);
refGrp = [ "EBID"];
[ uniqEBID, ~, JGrp]= unique( tdata( :, refGrp));
uniqEBID.maxLoss = accumarray( JGrp, tdata.Loss, [], @max);
instead of doing for loop below, can we use inline function with accumarray to do task below. Basically selecting other fields that has same index as maxLoss
for runi= 1: height( uniqEBID_Type)
tloc = (JGrp== runi);
tdata_i = tdata( tloc, :);
[ tmax, idx]= max( tdata_i.Loss);
uniqEBID.Peril( runi) = tdata_i.Peril( idx);
uniqEBID.Trial( runi) = tdata_i.Trial( idx);
end

채택된 답변

Matt J
Matt J 2025년 5월 17일
편집: Matt J 2025년 5월 18일
If by "inline function", you mean an anonymous function, then no. But you can certainly do it with a local function.
tdata = table([1 1 1 3 4 4 4 4]', ["eq","fr","wt","fl","eq","fr","fl","tr"]', [24 55 10 5 3 5 7 9 ]', int64([ 5 2 7 1 50 10 5 5 ]'),...
'VariableNames',["EBID","Peril","Loss","Trial"]);
refGrp = [ "EBID"];
uniqEBID=splitapply(@aggregate, tdata, findgroups(tdata.(refGrp)) )
uniqEBID = 3×4 table
EBID Peril maxLoss Trial ____ _____ _______ _____ 1 "fr" 55 2 3 "fl" 5 1 4 "tr" 9 5
function out=aggregate(EBID,Peril,Loss,Trial)
[maxLoss,idx]=max(Loss);
out=table(EBID(idx),Peril(idx), maxLoss,Trial(idx), ...
'Var',{'EBID','Peril', 'maxLoss','Trial'});
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Function Creation에 대해 자세히 알아보기

태그

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by