필터 지우기
필터 지우기

Adding Data to a structure

조회 수: 177 (최근 30일)
Glenn
Glenn 2012년 6월 6일
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

채택된 답변

Walter Roberson
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
Glenn
Glenn 2012년 6월 6일
Thanks. I made that work.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Oleg Komarov
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
Glenn
Glenn 2012년 6월 6일
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 2012년 6월 6일
Preallocation is not mandatory.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by