MATLAB: How to read the contents of a text file and save it as a structure in the MATLAB 7.8 (R2009a)

MATLABstructuretextreadtextscan

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.

Best Answer

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);
Related Question