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

조회 수: 18 (최근 30일)
Terez
Terez 2014년 6월 25일
댓글: Terez 2014년 6월 25일
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.

채택된 답변

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

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

추가 답변 (1개)

dpb
dpb 2014년 6월 25일
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.

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by