Effacer les filtres
Effacer les filtres

Adding Data to a structure

177 vues (au cours des 30 derniers jours)
Glenn
Glenn le 6 Juin 2012
I know this must be simple but I just can't find it. I have a loop which loads data from files. I produce a structure from the data in the file. How do I add more entries (not fields) to the structure on the next pass of the loop. What I am looking for is a single structure (collected_a) which has all of the data from multiple files. The example below doesn't work as you can't reference a structure as (end +1). What is the right way to do this?
for i = 1:10
fid=fopen(file(i))
FormatString=repmat('%s',1,78);
chaninfo = textscan(fid,FormatString,'CollectOutput',1);
fclose(fid);
columnHeadings = {'Reading' 'Station' 'Line' 'RL' 'Lat' 'Long' 'Loop' 'Chan' 'Axis' 'NumChans' 'Time'};
a = cell2struct(dat(:,2:12),columnHeadings,2);
collected_a(end +1) = a;
end

Réponse acceptée

Walter Roberson
Walter Roberson le 6 Juin 2012
(end+1) is fine for adding a single entry:
>> foo = struct('cliche', {'bird in hand'}, 'accuracy', {1/2})
foo =
cliche: 'bird in hand'
accuracy: 0.5
>> foo(end+1) = struct('cliche', {'stitch in time'}, 'accuracy', {1/9})
foo =
1x2 struct array with fields:
cliche
accuracy
If you are adding multiple entries, then use (end+1 : end+length(a))
  1 commentaire
Glenn
Glenn le 6 Juin 2012
Thanks. I made that work.

Connectez-vous pour commenter.

Plus de réponses (1)

Oleg Komarov
Oleg Komarov le 6 Juin 2012
A reduced example, try to port it to your case:
columnHeadings = {'Reading' 'Station'};
% Preallocate structure
a(1:10) = cell2struct(repmat({[]},numel(columnHeadings),1),columnHeadings,1);
% I am assuming the data has always the same number of fields (cells)
dat = {rand(10),rand(20)};
for i = 1:10
a(i) = cell2struct(dat',columnHeadings,1);
end
  2 commentaires
Glenn
Glenn le 6 Juin 2012
Thanks for the quick response. Unfortunately, can't preallocate as I don't know how many entries are in each file.
Oleg Komarov
Oleg Komarov le 6 Juin 2012
Preallocation is not mandatory.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by