using textscan to separate columns by delimiter
14 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Stephen23
il 3 Ott 2017
fid = textscan(fid,'Delimiter');
most likely should be
C = textscan(fid,'Delimiter');
Risposte (2)
Star Strider
il 3 Ott 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 Commenti
OCDER
il 3 Ott 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 Commenti
Vedere anche
Categorie
Scopri di più su Text Data Preparation in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!