Remove the Last Entry of Many Fields of a Structure
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Allen Hammack
le 8 Nov 2021
Commenté : Allen Hammack
le 8 Nov 2021
I have a multiple structures with many fields, and each field has thousands of entries (rows). I need the each field in a particular structure to have the same number of entries (rows). For instance, here is a sample of my situation:
data.test1=1:10;
data.test2=3:12;
data.test3=2:11;
data.test4=1:10;
data.test5=2:10;
data.test6=4:12;
data.test7=5:13;
data = structfun(@transpose,data,'UniformOutput',false);
How can I trim the last entry (row) from data.test1, data.test2, data.test3, and data.test4 programmatically? (In my real structures, I have many more fields, so I would prefer to not trim each field one at a time. I would greatly prefer to trim all the necessary fields in one command.) Will someone please help?
0 commentaires
Réponse acceptée
Adam Danz
le 8 Nov 2021
dataTrimmed = structfun(@(s)s(1:end-1),data,'UniformOutput',false);
3 commentaires
Adam Danz
le 8 Nov 2021
Sorry, I misunderstood. Here's how to do that,
data.test1=1:10;
data.test2=3:12;
data.test3=2:11;
data.test4=1:10;
data.test5=2:10;
data.test6=4:12;
data.test7=5:13;
data = structfun(@transpose,data,'UniformOutput',false)
% Get min count
minCount = min(structfun(@numel, data))
% trim to min count
dataTrimmed = structfun(@(s)s(1:minCount),data,'UniformOutput',false)
Plus de réponses (1)
Sean de Wolski
le 8 Nov 2021
data.test1=1:10;
data.test2=3:12;
data.test3=2:11;
data.test4=1:10;
data.test5=2:10;
data.test6=4:12;
data.test7=5:13;
n = structfun(@numel,data);
toremove = n-min(n);
fn = fieldnames(data);
for ii = 1:numel(fn)
data.(fn{ii}) = data.(fn{ii})(1:(numel(data.(fn{ii}))-toremove(ii)));
end
struct2table(data)
The interior of that loop could obviously be made clearer but I'll leave that as an exercise.
Voir également
Catégories
En savoir plus sur Structures dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!