我有一個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
都是細胞相同的長度,這樣我可以在一次設置多個領域。
第二個錯誤是'for kk = 1:nueml(missing_fields {{jj}})' - 我忘記了{{jj}} – telemachos 2013-02-14 10:11:50