Vertical concatenation of structure fields

조회 수: 49 (최근 30일)
Initial Conditions
Initial Conditions 2014년 9월 23일
댓글: Kelly Kearney 2014년 9월 23일
Hi,
I have a structure 'all' which has 45 fields with names 'day_X' where X goes from 1 to 45. Each 'day_X' level has 19 fields and it is these fields I want to concatenate. The fields are all vectors, and each Day_X struct has the same structure (fieldnames).
In other words, I want to vertically concatenate all.day_1.field1 through all.day_45.field1 , for each field. Is there an efficient way of doing this i.e., without a loop? I've tried numerous things, including a loop, but I know this can probably be done in a few lines.
Thanks in advance.

채택된 답변

Kelly Kearney
Kelly Kearney 2014년 9월 23일
I'd do it with one loop and one cellfun. You might be able to eliminate the loop entirely, but this keeps it a little more readable, in my opinion.
all.day1.one = 1;
all.day2.one = 2;
all.day1.two = 3;
all.day2.two = 4;
fld1 = fieldnames(all);
fld2 = fieldnames(all.day1);
for ii = 1:length(fld1)
tmp = cellfun(@(x) all.(x).(fld2{ii}), fld1, 'uni', 0);
A.(fld2{ii}) = cat(1, tmp{:});
end
  댓글 수: 3
Initial Conditions
Initial Conditions 2014년 9월 23일
Ok, simple mistake. The loop needs to be 1:length(fld2) not length(fld1)
Thanks!
Kelly Kearney
Kelly Kearney 2014년 9월 23일
Oops, yeah, typo.

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

추가 답변 (1개)

Guillaume
Guillaume 2014년 9월 23일
First of all, do not name your structure all as that shadows the name of a very useful matlab function.
Secondly, having a structure the way you've done it a bad idea (as you've just found out). You should have made the day field a structure array and the same with the field field.
Anyway, to answer your question:
c = cellfun(@(fn) all.(fn).field1, fieldnames(all), 'UniformOutput', false);
vertfield1 = vertcat(c{:});
  댓글 수: 1
Initial Conditions
Initial Conditions 2014년 9월 23일
Thanks for the neat solution. I realised all was a bad name when I tried to 'clear all' and not every variable was cleared! Your solution works but I still have to cycle through all the 19 variables starting with 'field1' - but this could be done in a quick loop I think.

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by