Remove the Last Entry of Many Fields of a Structure

조회 수: 11 (최근 30일)
Allen Hammack
Allen Hammack 2021년 11월 8일
댓글: Allen Hammack 2021년 11월 8일
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?

채택된 답변

Adam Danz
Adam Danz 2021년 11월 8일
dataTrimmed = structfun(@(s)s(1:end-1),data,'UniformOutput',false);
  댓글 수: 3
Adam Danz
Adam Danz 2021년 11월 8일
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)
data = struct with fields:
test1: [10×1 double] test2: [10×1 double] test3: [10×1 double] test4: [10×1 double] test5: [9×1 double] test6: [9×1 double] test7: [9×1 double]
% Get min count
minCount = min(structfun(@numel, data))
minCount = 9
% trim to min count
dataTrimmed = structfun(@(s)s(1:minCount),data,'UniformOutput',false)
dataTrimmed = struct with fields:
test1: [9×1 double] test2: [9×1 double] test3: [9×1 double] test4: [9×1 double] test5: [9×1 double] test6: [9×1 double] test7: [9×1 double]
Allen Hammack
Allen Hammack 2021년 11월 8일
That's perfect! thank you so much!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Sean de Wolski
Sean de Wolski 2021년 11월 8일
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)
ans = 1×7 table
test1 test2 test3 test4 test5 test6 test7 __________ __________ __________ __________ __________ __________ __________ 1×9 double 1×9 double 1×9 double 1×9 double 1×9 double 1×9 double 1×9 double
The interior of that loop could obviously be made clearer but I'll leave that as an exercise.

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by