using textscan to separate columns by delimiter
14 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
Stephen23
le 3 Oct 2017
fid = textscan(fid,'Delimiter');
most likely should be
C = textscan(fid,'Delimiter');
Réponses (2)
Star Strider
le 3 Oct 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.
0 commentaires
OCDER
le 3 Oct 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
0 commentaires
Voir également
Catégories
En savoir plus sur Text Data Preparation dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!