Yogesh
Yogesh

Reputation: 49

Reading CSV file with text using textread

I am reading a csv file in Matlab using textread function and storing the values in the cells of string and float types.

[string1, string2, values] = textread('/path/xyz.csv', '%s %s %f', 'headerlines', 1);

Data has three columns. Two of them I believe are of string type and one is float.

Sample Data

@timestamp  host    value
March 5th 2019, 13:41:54.879    tscompute1  0.399
March 5th 2019, 13:41:54.879    tscompute1  0.599
March 5th 2019, 13:41:54.879    tscompute1  0
March 5th 2019, 13:41:54.879    tscompute1  0.2
March 5th 2019, 13:41:54.879    tscompute1  0
March 5th 2019, 13:41:54.879    tscompute1  0
March 5th 2019, 13:41:54.879    tscompute1  0
March 5th 2019, 13:41:54.879    tscompute1  0
March 5th 2019, 13:41:54.879    tscompute1  0
March 5th 2019, 13:41:54.879    tscompute1  100
March 5th 2019, 13:41:54.879    tscompute1  0.4

There is not execution error. But the read values are not as expected. Please find the sample output below.

Values stored in string1 looks like as follows

'"March'
','
'"March'
','
'"March'
','
'"March'
','

Values stored in string2 looks like as follows

'5th'
'13:41:54.879",tscompute1,0.399'
'5th'
'13:41:54.879",tscompute1,0.599'
'5th'
'13:41:54.879",tscompute1,0'
'5th'
'13:41:54.879",tscompute1,0.2' 

Values stored in values looks like as follows

2019
0
2019
0
2019
0
2019
0

Upvotes: 1

Views: 276

Answers (1)

NoDataDumpNoContribution
NoDataDumpNoContribution

Reputation: 10859

Your text seems to have inconsistent delimiters, the date is separated from the time by a comma, while the time, the name "tscompute1" and the number are separated by white-spaces.

The simplest is to read every line as six elements each separated by white-spaces with five of them being strings and the sixth being a number.

[s1, s2, s3, s4, s5, values] = textread('/path/xyz.csv', '%s %s %s %s %s %f', 'headerlines', 1);

That allows you to get the date (concatenate strings in s1-s3, remove the trailing comma), the time (s4), the name (s5) and the value.

Upvotes: 1

Related Questions