readtable using space as unwanted delimiter

조회 수: 61 (최근 30일)
Callum Clarke
Callum Clarke 2016년 6월 30일
댓글: Star Strider 2016년 7월 1일
I have a CSV that includes a field containing multiple numbers separated by spaces that I would like to read as a single column. My data is of the form:
name,var1,var2,var3,var4
some name,1.1,2.2,3.3,44 5.5
other name,6.6,7.7,8.8,99 0.0
I would like it to be output as:
name var1 var2 var3 var4
__________ ____ ____ ____ _________
some name 1.1 2.2 3.3 44 5.5
other name 6.6 7.7 8.8 99 0.0
The problem is using readtable() reads the spaces in the last column as delimiters. I have tried explicitly setting the delimiter:
data = readtable(file, 'Delimiter', ',');
To no avail. It seems to work on strings, just not on numbers. I would prefer to not explicitly define the format as column order may change. If it can't be done easily I can always resort to a custom reader using textscan()...

답변 (2개)

Guillaume
Guillaume 2016년 7월 1일
Possibly, this would work (or a variation upon it):
data = readtable(file, 'Delimiter', ',', 'Format', '%s,%f,%f,%f,%s')
That is override the format of the row to force interpretation of the last two numbers as a string.

Star Strider
Star Strider 2016년 6월 30일
I don’t use readtable much, but looking through the documentation, there are options you may want to consider. One is 'TreatAsEmpty' and another is 'FileType'. I don’t have your file to experiment with, so I can’t suggest anything more specific.
  댓글 수: 2
Callum Clarke
Callum Clarke 2016년 7월 1일
I had a look through the readtable script, which ends up calling readfromfile > readtextfile > textscan. Turns out readtextfile infers the structure from the first row, which in my data only has a single value in the column that should allow multiple values. Custom code it is then!
Star Strider
Star Strider 2016년 7월 1일
You should be able to do it with textscan. It’s flexible enough to be able to read your file, although you might have to write a separate fscanf (or textscan) call to read the first line.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by