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

18 Ansichten (letzte 30 Tage)
Terez
Terez am 25 Jun. 2014
Kommentiert: Terez am 25 Jun. 2014
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.

Akzeptierte Antwort

A Jenkins
A Jenkins am 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 Kommentare
A Jenkins
A Jenkins am 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 am 25 Jun. 2014
I was originally getting an error when I put a tab between distance and elevation but your code worked thank you!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

dpb
dpb am 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.

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by