Wednesday, November 18, 2009

Read Text with Mixed Data and Delimiter (Matlab)

In Matlab, if we have to read text with mixed data (numerical and alphanumerical data) and the text has delimiter, we can use textscan.

for example:

if the text file contains the following data:

<TICKER>,<PER>,<DTYYYYMMDD>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>,<OPENINT>
HU___1985G,D,19841203,000000,0.7180,0.7250,0.7160,0.7245,221,165
HU___1985G,D,19841204,000000,0.7275,0.7290,0.7240,0.7254,75,220
HU___1985G,D,19841205,000000,0.7190,0.7250,0.7165,0.7230,267,390

Then we can write the code like:

fid = fopen(filename);
c = textscan(fid, '%s %s %d %s %n %n %n %n %n %n' ,'delimiter', ',', 'headerLines', 1);
fclose(fid);

Here the delimiter is ',' and the function will skip 1 line of header.