How to do inline function with unique instead of using for loop
조회 수: 4 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
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)) )
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!