필터 지우기
필터 지우기

Delimiting a text file like "Text to columns"

조회 수: 14 (최근 30일)
Brian
Brian 2011년 9월 14일
Hello, I am trying to import data from a Text file (.txt). This data has a single column of mixed (numeric and string) data that is | (bar) delimited. My goal is to import this data and seperate each delimited portion into a seperate columns while maintaining the rows. Essentially, I am trying to do the Excel "Text to columns" with MATLAB. Thank you

채택된 답변

Walter Roberson
Walter Roberson 2011년 9월 14일
%open file
fid = fopen(YourFile,'rt');
%figure out how many columns are there
firstline = fgetl(fid);
ncol = 1 + sum(firstline == '|');
%reset to beginning of file
fseek(fid,0,0);
%read data
indata = textscan(fid,repmat('%s',1,ncol),'Delimiter','|','CollectOutput',1);
%close file
fclose(fid);
The result will be indata, a cell array of strings.
  댓글 수: 4
Brian
Brian 2011년 9월 14일
How do I look at indata's data? Below is a step-by-step output:
>> fid = fopen('RMS_Functional_Block_Report.txt','rt')
fid =
5
>> firstline = fgetl(fid)
firstline =
RMS Functional Block|Reference Designator|Part Number|Sheet Number|Description|Invisible
>> ncol = 1 + sum(firstline == '|')
ncol =
6
>> fseek(fid,0,0)
ans =
0
>> indata = textscan(fid,repmat('%s',1,ncol),'Delimiter','|','CollectOutput',1)
indata =
{646x6 cell}
>> fclose(fid)
ans =
0
Walter Roberson
Walter Roberson 2011년 9월 15일
indata{L,C} will be the string that was on line #L at column #C
For example, indata{3,7} is column 7 of line 3.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by