How do I separate data into columns from a text file?

18 views (last 30 days)
I'm trying to load data from a text file that had a heading, two column headers and 50 or so rows of data. Attached is a picture. I'm using the readtable function [readtable(filename)] but the problem is that when matlab puts the data in an array it combines the two columns of data and puts the numbers together separated by decimal points. How do I set the two headings as separate columns and put the data underneath these headings? First picture is the data and the second is the output from matlab.

Accepted Answer

A Jenkins
A Jenkins on 25 Jun 2014
Have you tried using the Import Wizard? You can adjust your delimiters and header rows until it looks right, and there is even an option to generate code for you. Then you can edit the code or save it later to get exactly what you want.
In your case, at least you will want to set the 'Delimiter' option to '\t'. (It is ',' by default.)
  2 Comments
A Jenkins
A Jenkins on 25 Jun 2014
Agreed with dqb's suggestion. If you put the tab in between Distance and Elevation, you can just do this:
>> readtable('untitled.txt','Delimiter','\t','HeaderLines',1)
ans =
distance elevation
________ _________
-53.36 25.47
-50.19 26.73
-32.18 13.21
Terez
Terez on 25 Jun 2014
I was originally getting an error when I put a tab between distance and elevation but your code worked thank you!

Sign in to comment.

More Answers (1)

dpb
dpb on 25 Jun 2014
Problem is there's no separation between the two column headers so readtable thinks there's to be only one variable. Either fix the input file to fix that problem (may also need to tell it to skip the preceding headerline as well, not sure how smart it is as my version doesn't include it). You can see this is a problem as the first row shows the variable name as 'DistanceElevation' instead of two variables.
It doesn't appear there's an option to skip the two headerlines and manually set a header line value for variable names--if you ignore them it just uses some default names so looks like your best bet is to either
a) fix the file format, or if that's not feaible
b) use one of the other input forms and set the variable names in the table manually after reading.

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!