Error using textscan, when trying to read in the first two columns of a text file

1 view (last 30 days)
I am trying to use the following code to read in a text file.
%Get events from text file
prompt_totalfiles = 'Enter number of files you want to input: '; %asks for number of files
total_files = input(prompt_totalfiles);
fileNames = cell(total_files,1);
for file = 1:total_files
[inputfile,path] = uigetfile('*.txt');
fileNames{file} = fopen(inputfile);
end
j = 1;
Baseline_adjustment = 0.1; %put in baseline photodetector value here (the readout with the led on but the patch cable in pitch black
dff1=[];dff2=[];dff3=[];dff4=[];dff5=[];dff6=[];dff7=[];dff8=[];dff9=[];dff10=[];dff11=[];
wholedff={dff1,dff2,dff3,dff4,dff5,dff6,dff7,dff8,dff9,dff10,dff11};
%Read formatted data from text file
for file = 1:total_files
b = textscan(fileNames{file},'%n %n', -1, 'delimiter', '/t');
This is the error I receive:
Error using textscan
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in StimulusTestNew (line 17)
b = textscan(fileNames{file},'%n %n', -1, 'delimiter', '/t');
The text file I wanna read in is this: I want to read in only the first two columns.
Can you please help me? Thanks!

Accepted Answer

Guillaume
Guillaume on 1 May 2020
"Invalid file identifier. Use fopen to generate a valid file identifier."
You will typically get this error because the file id that fopen gave you is -1 which indicates that fopen failed to open the file.
There are many reasons why fopen could fail to open the file. The most likely one is because you asked it to open a file that didn't exist (at least in the location where you told it to look).
For a start you retrieve the path of the selected with uigetfile but never tell fopen to look in that path.
filenames{file} = fopen(fullfile(path, inputfile));
may fix the problem. Of course, you should always check that fopen succeeded, so add:
if filenames{file} == -1
error('Failed to open file "%s"', fullfile(path, inputfile));
end
I would strongly recommend renaming that filenames variable to something else, fileids maybe as it absolutely does not contain filenames. It contains file indentifiers: numbers.
Also, I would strongly recommend opening, reading, and closing the file in the same loop rather than doing it over 3 different loops. However, if you're using any reasonably recent version of matlab, I'd recommend using readtable instead of textscan. readtable should figure the format of the file on its own, and opens and closes the file for you.
Finally, note that numbered variables are always a bad idea, forcing you to write a lot more code than necessary. Here you could have created wholedff with just:
wholedff = cell(1, 11);

More Answers (0)

Community Treasure Hunt

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

Start Hunting!