MATLAB: Open multiple files with fopen

opentext file

I have written two codes in matlab:
The first one is:
files=dir('*.csv');
for i=1:length(files)
fid(i)=fopen(files(i).name);
files(i).values=textscan(fid(i), '%f %f','delimiter',',','HeaderLines',20,'MultipleDelimsAsOne',1);
end
and the second one is:
str='C:\Users\user\Measurements\Test';
folder_name=uigetdir(str);
files=dir(fullfile(folder_name,'*.csv'));
for i=1:length(files)
fid(i)=fopen(files(i).name);
files(i).values=textscan(fid(i), '%f %f','delimiter',',','HeaderLines',20,'MultipleDelimsAsOne',1);
end
The first code is saved in the same folder as the files that I want to open. The second code is saved outside the folder where the files are stored. But both should read the same files. In the first code the structure files.values is composed by a 1×2 cell. Both cells contain a column vector with numerical values The problem arises in the second code which sometimes gives me an error because fid=-1 or the column vectors in the structure files.values are empty.
How can I overcome this problem?

Best Answer

Ok solved myself. The problem was that I was using textscan outside the current folder. Therefore I changed the folder to the folder of interest and back to the initial folder.
str='C:\Users\user\Measurements\Test';
folder_name=uigetdir(str);
files=dir(fullfile(folder_name,'*.csv'));
curr_folder=pwd;
cd(folder_name);
for i=1:length(files)
[fid(i),msg]=fopen(files(i).name);
disp(msg);
files(i).values=textscan(fid(i), '%f %f','delimiter',',',...
'Headerlines',20,...
'MultipleDelimsAsOne',1);
fclose(fid(i));
end
cd(curr_folder)