using textscan to separate columns by delimiter

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 Comment

fid = textscan(fid,'Delimiter');
most likely should be
C = textscan(fid,'Delimiter');

Sign in to comment.

Answers (2)

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.
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

Categories

Products

Asked:

on 3 Oct 2017

Answered:

on 3 Oct 2017

Community Treasure Hunt

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

Start Hunting!