How do I read the contents of a text file and save it as a structure in the MATLAB 7.8 (R2009a)?
6 views (last 30 days)
Show older comments
I have text file that contains alphanumeric data. The example data file 'myfile.txt' is as follows:
1,headache,1
2,fever,1
3,chest Pain,1
I want to read the data from 'myfile.txt' and save it as a structure in the MATLAB workspace.
Accepted Answer
MathWorks Support Team
on 14 Jul 2009
The data in the text file cannot be directly saved to a structure in the MATLAB workspace. However, it is possible to read data using TEXTSCAN function and then format the data using STRUCT function to save it as a MATLAB structure. Sample code is as follows:
fid = fopen('myfile.txt');
%%Using textscan function to read all the lines in the file to C
C = textscan(fid, '%d %30s %d', 'delimiter', ',');
%%Using struct function to save the data read in to structure.
MedicalData = struct('ID', num2cell(C{1}), 'Disease', C{2}, 'num', num2cell(C{3}))
%%Closing the file after it is done reading.
fclose(fid);
0 Comments
More Answers (0)
See Also
Categories
Find more on Text Files 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!