Adding Data to a structure
177 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Walter Roberson
2012 年 6 月 6 日
(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 件)
Oleg Komarov
2012 年 6 月 6 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Get Started with MATLAB についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!