【问题标题】:setting multiple fields at once / add new field to a cell struct一次设置多个字段/将新字段添加到单元格结构
【发布时间】:2013-02-14 08:44:15
【问题描述】:

我有一个 1xn 结构。结构包含一些带有数字单元格的字段。并非每个结构都具有相同的字段。所以我想将缺少的字段添加到结构中。但我没听懂。

%  Mimimal example
%  I have same cells, imported from csv by csv2cell()

clear

dataCell{1}={"field_a","field_b","field_c"; ...
    1,2,3; ...
    4,5,6};

dataCell{2}={"field_a","field_b","field_d"; ...
    1,2,4; ...
    4,5,8};

%   Then I convert them to a struct
for ii=1:numel(dataCell)    
DataStruct{ii}=cell2struct((dataCell{ii}(2:end,:)),[dataCell{ii}(1,:)],2);
  try fields=[fields, fieldnames(DataStruct{ii})']; % fails for the first loop, because 'fields' doesn't exist yet
  catch
   fields=[fieldnames(DataStruct{ii})']; % create 'fields' in the first loop
  end
end

% Create a list of all existing fields
fields=unique(fields);

% Now look for the missing fields and add them to the struct
for jj=1:numel(DataStruct)
  missing_fields{jj} = setdiff(fields,fieldnames(DataStruct{jj}));
  for kk=1:numel(missing_fields)
    DataStruct{jj}.(missing_fields{jj}{kk})=NaN*zeros(numel(dataCell{jj}(2:end,1)),1); % Execution fails here!
  end
end

这会导致错误:

八度错误

error: invalid assignment to cs-list outside multiple assignment
error: called from:
error:   ~/example.m at line 29, column 44

Matlab 错误

Insufficient outputs from right hand side to satisfy comma separated
list expansion on left hand side.  Missing [] are the most likely cause.

问题是,DataStruct{1}.field_a 的输出不是矩阵或单元格,而是多个答案。是否有可能将单元格转换为矩阵或导入 csv 的更好可能性?

另一个很好的可能性是这样的

 DataStruct{jj}=setfields(missing_fields{jj},NaN_Values{jj})

其中missing_fields{jj}NaN_Values 都是长度相同的单元格,因此我可以一次设置多个字段。

【问题讨论】:

    标签: matlab octave


    【解决方案1】:

    您使用deal 函数将输出分配给输入。以您为例:

    % Now look for the missing fields and add them to the struct
    for jj=1:numel(DataStruct)
      missing_fields{jj} = setdiff(fields,fieldnames(DataStruct{jj}));
      for kk=1:numel(missing_fields)
        [DataStruct{jj}.(missing_fields{jj}{kk})] = deal(NaN*zeros(numel(dataCell{jj}(2:end,1)),1));
      end
    end
    

    请注意,您将收到 Index exceeds matrix dimensions,但这是由于另一个问题 - 我相信您将能够解决这个问题!

    【讨论】:

    • 第二个错误是 `for kk=1:nueml(missing_fields{{jj}})´ - 我忘记了 {{jj}}
    【解决方案2】:

    在您最后一个 question 之后 - 您可以使用 deal 命令。

    片段:

    a=struct('f1',num2cell(1:10))
    missing_field = 'test'
    [a.(missing_field)]=deal(NaN)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多