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

4 vues (au cours des 30 derniers jours)
Pete sherer
Pete sherer le 17 Mai 2025
Modifié(e) : Matt J le 18 Mai 2025
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

Réponse acceptée

Matt J
Matt J le 17 Mai 2025
Modifié(e) : Matt J le 18 Mai 2025
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

Plus de réponses (0)

Catégories

En savoir plus sur Function Creation dans Help Center et File Exchange

Tags

Produits


Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by