Filter löschen
Filter löschen

Adding Data to a structure

177 Ansichten (letzte 30 Tage)
Glenn
Glenn am 6 Jun. 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

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 6 Jun. 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 Kommentar
Glenn
Glenn am 6 Jun. 2012
Thanks. I made that work.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Oleg Komarov
Oleg Komarov am 6 Jun. 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 Kommentare
Glenn
Glenn am 6 Jun. 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 am 6 Jun. 2012
Preallocation is not mandatory.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by