MATLAB: Error using exist “The optional second input to exist must be ‘var’, ‘builtin’,’class’, ‘dir’ or ‘file’ “

existMATLAB

I don't understand why the following code doesn't work
for k = 1:4
% Create a text file name, and read the file.
textFileName = ['A' num2str(k) '.txt'];
if exist(textFileName, 'A')
fid = fopen(textFileName, 'rt');
mydata = fread(fid);
fclose(fid);
else
fprintf('File %s does not exist.\n', textFileName);
end
end

Best Answer

It looks like you're checking the existance of a certain file named something like "A1.txt" on the matlab path prior to reading that file. The exist() function has 1 mandatory input and 1 optional input. The optional input allows you to specify the type of result to search for. If you're searching for a file, one of those option for the 2nd input is 'file'.
The correct way to search for the existance of that file on the matlab path is:
if exist(textFileName, 'file')