Setting multiple fields at the same time / adding a new field to the cell structure

I have a 1xn structure. Structures contain some fields with numeric cells. Not every structure has the same fields. So I would like to add the missing fields to the structure. 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

      

This results in an error:

Octave error

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

      

Matlab error

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

      

The problem is that the output is DataStruct{1}.field_a

not a matrix or a cell, but several ans. Is there an easy way to convert cells to matrix, or better csv import option?

Another good possibility would be like this.

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

      

where missing_fields{jj}

and NaN_Values

are both cells with the same length, so I can set multiple fields at once.

+3


source to share


2 answers


You use a function deal

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

      



Note what you get Index exceeds matrix dimensions

, but this is related to a different issue - I'm sure you can sort this file!

+2


source


after your last question - you can use the deal command.

Excerpt:



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

      

+2


source







All Articles