using textscan to separate columns by delimiter

조회 수: 28 (최근 30일)
Nicole Canfield
Nicole Canfield 2017년 10월 3일
답변: OCDER 2017년 10월 3일
I am trying to import a csv file with data in one column that is separated by a space. I added a textscan line into the following code and am getting the following error Error using fgets Invalid file identifier. Use fopen to generate a valid file identifier.
n=length(Lines); fid=fopen(Path_FileName,'r'); fid = textscan(fid,'Delimiter'); while 1 tline = fgetl(fid); if m>n break end
  댓글 수: 1
Stephen23
Stephen23 2017년 10월 3일
fid = textscan(fid,'Delimiter');
most likely should be
C = textscan(fid,'Delimiter');

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

답변 (2개)

Star Strider
Star Strider 2017년 10월 3일
First, it would be easier to use csvread, dlmread, readtable, or others.
Note that this line overwrites the ‘fid’ value initially returned by your fopen call:
fid = textscan(fid,'Delimiter');
After this line, ‘fid’ is no longer a valid file identifier.

OCDER
OCDER 2017년 10월 3일
Here's how to open a file separated by space. See example data.txt.
FID = fopen(FileName, 'r'); %Open file to read, save the file ID
FstLine = fgetl(FID); %Get the 1st line
Columns = length(regexp(FstLine, '[\d\.]+', 'match')); %Use 1st line to count # of columns (any digit or decimal, [\d\.]+)
%OPTION 1: use fscanf
fseek(FID, 0, 'bof'); %Return to beginning of file
Data1 = fscanf(FID, '%f', [Columns, Inf])'; %Don't forget transpose at end
%OPTION 2: use textscan
fseek(FID, 0, 'bof'); %Return to beginning of file
Data2 = textscan(FID, repmat('%f', 1, Columns), 'CollectOutput', true, 'Delimiter', '\b\t'); %Requires a format like %f%f%f
Data2 = Data2{1}; %Data2 is a cell, so need to unwrap data from cell
fclose(FID); %Close the file

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by