一次设置多个字段/将新字段添加到单元格结构 [英] setting multiple fields at once / add new field to a cell struct
问题描述
我有一个1xn结构.该结构包含一些带有数字单元格的字段.并非每个结构都具有相同的字段.因此,我想将缺少的字段添加到该结构中.但是我不明白.
I have a 1xn struct. The structs contains some fields with numeric cells. Not every struct has the same fields. So I would like to add the missing fields to the struct. But I didn't get it.
% 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
的输出不是矩阵或单元格,而是多个ans.是否有将细胞转换为矩阵的简便方法,还是导入csv的更好方法?
The problem is, that the output of DataStruct{1}.field_a
is not a matrix or a cell, but multiple ans. Is there a easy possibility to convert the cells to a matrix or a better possibility to import the csv?
另一个好的可能性就是这样
the other good possibility would be something like this
DataStruct{jj}=setfields(missing_fields{jj},NaN_Values{jj})
其中missing_fields{jj}
和NaN_Values
都是长度相同的单元格,因此我可以一次设置多个字段.
where missing_fields{jj}
and NaN_Values
are both cells with the same length, so that i can set multiple fields at once.
推荐答案
您可以使用deal
函数将输出分配给输入.例如:
You use the deal
function to distribute output to inputs. For your example:
% 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
,但这是由于另一个问题所致-我相信您将能够解决该问题!
Note that you will get an Index exceeds matrix dimensions
, but this is due to a different problem - I'm sure you'll be able to sort that one out!
这篇关于一次设置多个字段/将新字段添加到单元格结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!