How to read a text file and create a structure array?

조회 수: 17 (최근 30일)
Jay
Jay 2013년 2월 12일
Hey,
I have a large data set which is divided into 3 columns and and in two separate text files. I would like to read the data from text files, add the data together so that it is in continuous columns and create a structure from it.
The text files' data is like:
$ABC, 00025, 39.24
. , . , .
. , . , .
I tried this code:
fid = fopen('mydata.txt');
C = textscan(fid, '%s%d8%f32');
fclose(fid);
f = {'Title','Time','Dist'};
s = cell2struct(C,f,2);
but it returns a blank structure array. Can somebody please tell me what is wrong with the code?
Thanks.

채택된 답변

ChristianW
ChristianW 2013년 2월 13일
Try to skip the second comma.
C = textscan(fid, '%s%d8%*s%f32');
  댓글 수: 2
Jay
Jay 2013년 2월 13일
Thanks, works like a charm.
Now what if I have a second set of similar data which is a continuation of the first. Say mydata2.txt. How do I read this into matlab as well and add it to the first data set to create a single cell array?
ChristianW
ChristianW 2013년 2월 14일
A simple possibility is to load the 2nd file in a 2nd cell and combine them in a for loop.
...
fid = fopen('mydata2.txt');
C2 = textscan(fid,'%s %d8 %f32','delimiter',',');
fclose(fid);
for i = 1:numel(C1)
C{i} = [C1{i}; C2{i}];
end
...

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by