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

조회 수: 2 (최근 30일)
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!

채택된 답변

Guillaume
Guillaume 2020년 5월 1일
"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);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by