0
votes

I have a file test.txt looks like:

datetime season holiday workingday weather atemp humidity

2011/1/1 0:00 1 0 0 1 cold high
2011/1/1 1:00 1 0 0 1 cold high

I want to import them into matlab by delimiter "\t". However, a=importdata('test.txt','\t') just import data as a whole rather than separating by \t.

I also try other command like dlmread:

Error using dlmread (line 139) Mismatch between file and format string. Trouble reading number from file (row 1u, field 1u) ==> datetime season holiday workingday weather atemp humidity\n

then i try str1=textsacn('test.txt','%s%s%s%s%s%s%s');

Undefined function 'textsacn' for input arguments of type 'char'.

My matlab version is 2012a. I use windows. could anyone help?

2

2 Answers

0
votes

importdata and dlmread are for numerical data. For a mix text/numerical you have to use textscan (you have a typo on textsacn) with fopen and fclose, and then reformat your cell array with reshape:

fid = fopen('test.txt');
s = textscan(fid,  '%s', 'Delimiter', '\t');
fclose(fid);

s = reshape(s{1}, [7 numel(s{1})/7])';

and the output:

s = 
    '2011/1/1 0:00'    '1'    '0'    '0'    '1'    'cold'    'high'
    '2011/1/1 1:00'    '1'    '0'    '0'    '1'    'cold'    'high'

Then, some strings like '0' or '1' can be converted to numbers with str2num.

Best,

0
votes

You can also use textscan and specify the numeric format directly:

fid = fopen('test.txt');
out = textscan(fid, '%s%d%d%d%d%s%s', 'Delimiter', '\t')
fclose(fid);

This way the variable out already contains numbers for the four numeric columns. You can convert the first column to datenum by doing:

dates = datenum(out{1});