Read all the columns in a .csv file
Show older comments
Hi,
I have a .csv file with the following columns, I need to read all the columns. What function I need to use. I tried csvread but it did not work.
KH 110427 PH M 1951-01-01T07:00:00+07:00 0 mm O
KH 110427 PH M 1951-01-02T07:00:00+07:00 0 mm O
KH 110427 PH M 1951-01-03T07:00:00+07:00 0 mm O
.
.
.
Any ideas?
Thanks.
Accepted Answer
More Answers (1)
Image Analyst
on 29 Oct 2014
If you make the first row a line of tab separated names for the columns....
col1 col2 col3 col4 col5 col6 col7 col8
KH 110427 PH M 1951-01-01T07:00:00+07:00 0 mm O
KH 110427 PH M 1951-01-02T07:00:00+07:00 0 mm O
KH 110427 PH M 1951-01-03T07:00:00+07:00 0 mm O
Then you could use readtable() which gives a table rather than a cell array. I find tables are easier to use than cell arrays where you always have to figure out whether you want to use braces or parentheses.
t=readtable('test2.csv', 'delimiter', '\t')
When I ran it.....
>> test2
t =
col1 col2 col3 col4 col5 col6 col7 col8
____ __________ ____ ____ ___________________________ ____ ____ ____
'KH' 1.1043e+05 'PH' 'M' '1951-01-01T07:00:00+07:00' 0 'mm' 'O'
'KH' 1.1043e+05 'PH' 'M' '1951-01-02T07:00:00+07:00' 0 'mm' 'O'
'KH' 1.1043e+05 'PH' 'M' '1951-01-03T07:00:00+07:00' 0 'mm' 'O'
8 Comments
Damith
on 29 Oct 2014
Image Analyst
on 29 Oct 2014
If you add the column names row, it does work. Try the line of code
t=readtable('test2.csv', 'delimiter', '\t')
on the attached csv file. It WILL work (assuming you have R2013b or later which is required for tables).
Damith
on 29 Oct 2014
Image Analyst
on 29 Oct 2014
You said "I have a .csv file with the following columns" so I copied what you put down. Then I added the header line. What does "But all .csv files does look like output (t)." mean? If they all do look like that, then that's good, isn't it? If you want to actually attach your file with the paperclip icon, go ahead.
Damith
on 30 Oct 2014
Image Analyst
on 30 Oct 2014
My code was dependent on you being able to add a line with column headers. I'm assuming that you created the CSV files in MATLAB or some other program that you have control over. Can you do that? If not try using textscan like Star suggested. It's a little more complicated because you'll have to parse the string and figure out the format specifier string, but it can be done.
Damith
on 30 Oct 2014
Image Analyst
on 30 Oct 2014
I just did it manually in the text editor. If you wanted to ad a preprocessing step where you open all the files and add that headerline, you could easily do that with the code in the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!