MATLAB structure merge

落花浮王杯 提交于 2019-12-06 04:49:28

问题


I have the following struct

data = 

                       id: [143x1 double]
                  datenum: [143x1 double]
                Timestamp: {143x1 cell}
         Min_F1_USA_40__u: [143x1 double]
         Max_F1_USA_40__u: [143x1 double]
        Mean_F1_USA_40__u: [143x1 double]
      Stddev_F1_USA_40__u: [143x1 double]
    MeanVals_F1_USA_40__u: [143x1 double]
          a0_F1_USA_40__u: [143x1 double]
          a1_F1_USA_40__u: [143x1 double]
          a2_F1_USA_40__u: [143x1 double]
          a3_F1_USA_40__u: [143x1 double]
      a4_F1_USA_40__u: [143x1 double]

So on, I have more than 50 field in the struct

I have other 3 structure with the same structure and I want to merge this struct

When I have 3 struct I will get the following structure

data = 

                       id: [429x1 double]
                  datenum: [429x1 double]
                Timestamp: {429x1 cell}
         Min_F1_USA_40__u: [429x1 double]
         Max_F1_USA_40__u: [429x1 double]
        Mean_F1_USA_40__u: [429x1 double]
      Stddev_F1_USA_40__u: [429x1 double]
        .
        .
        .

回答1:


Sorry, I had misunderstood your question - here a second try.

Maybe there is an easier way, but you can get a list of all fields in data using mynames=fieldnames(data). You can then loop through them all and assign them to a common struct like this:

combineddata.(mynames{i})=[data1.(mynames{i}); data2.(mynames{i}); data3.(mynames{i})];



回答2:


Here's one solution using the functions FIELDNAMES, CELLFUN, and CELL2STRUCT:

data = [data1 data2 data3 data4];    %# Create a structure array of your data
names = fieldnames(data);            %# Get the field names
cellData = cellfun(@(f) {vertcat(data.(f))},names);  %# Collect field data into
                                                     %#   a cell array
data = cell2struct(cellData,names);  %# Convert the cell array into a structure


来源:https://stackoverflow.com/questions/5882177/matlab-structure-merge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!