Adding Data to a structure
177 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Walter Roberson
on 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))
More Answers (1)
Oleg Komarov
on 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 Comments
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!