2013-02-14 79 views
3

我有一个1xn结构。结构包含一些带有数字单元格的字段。不是每个结构都有相同的字段。所以我想将缺少的字段添加到结构中。但我没有明白。一次设置多个字段/向单元添加新字段struct

% 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都是细胞相同的长度,这样我可以在一次设置多个领域。

回答

2

您使用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,但是这是由于不同的问题 - 我敢肯定,你就可以到一个理清!

+0

第二个错误是'for kk = 1:nueml(missing_fields {{jj}})' - 我忘记了{{jj}} – telemachos 2013-02-14 10:11:50

2

继最后的question之后 - 您可以使用deal命令。

段:

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