using textscan to separate columns by delimiter

19 Ansichten (letzte 30 Tage)
Nicole Canfield
Nicole Canfield am 3 Okt. 2017
Beantwortet: OCDER am 3 Okt. 2017
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 Kommentar
Stephen23
Stephen23 am 3 Okt. 2017
fid = textscan(fid,'Delimiter');
most likely should be
C = textscan(fid,'Delimiter');

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Star Strider
Star Strider am 3 Okt. 2017
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 am 3 Okt. 2017
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

Kategorien

Mehr zu Text Data Preparation finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by