How to open multiple text files and populating matrices with the data

3 ビュー (過去 30 日間)
Md. Golam Mostafa
Md. Golam Mostafa 2016 年 11 月 19 日
編集済み: Md. Golam Mostafa 2016 年 11 月 21 日
I have written the following codes to open a text file and populate a matrix with the data. It works fine.
fid=fopen('01_06_13hi.txt'); %Opens the file
allData =[]; %Creats a matrix to store all data
n = 0;
while feof(fid)== 0;
d1 = fgetl(fid); % reading the file line by line
if strfind(d1,'-NaN') %Overrules the 'Not a Number' value
else
n=n+1;
ind= find(d1(:)==':'); %finds ':' in the data string and storing in variable 'ind'
ind2 = find(d1(:)=='/'); %finds '/' in the data string and storing in variable 'ind2'
d1(ind) = ' '; %string data
d1(ind2) = ' '; %string data
d2 = str2num(d1); % converting the data from string to number
allData(n,:) = d2; %Storing data of d2
end
end
Now I have some 630 .txt files. I have tried to modify the the code as follows:
filesFolder = 'lo_hi1/';
allTextFiles = dir([filesFolder,'*.txt']);
numberOfTextFiles = numel(allTextFiles);
nameOfTextFiles = {allTextFiles.name};
allData =[];
n = 0;
for i=1:numberOfTextFiles
fileID=fopen(nameOfTextFiles{i});
while feof(fileID)== 0;
d1 = fgetl(fileID);
if strfind(d1,'-NaN')
else
n=n+1;
ind= find(d1(:)==':');
ind2 = find(d1(:)=='/');
d1(ind) = ' ';
d1(ind2) = ' ';
d2 = str2num(d1);
allData(n,:) = d2;
end
end
fclose(fileID); %closing the file
end
I expected it to work but unfortunately it is not working. The command window showed the following:
Error using feof Invalid file identifier. Use fopen to generate a valid file identifier.
Error in multifileload (line 15) while feof(fileID)== 0;
Can anyone help me out?
  2 件のコメント
dpb
dpb 2016 年 11 月 19 日
Well, what does "not working" mean, precisely? We don't have your data so can't run it and can't see your terminal from here, either...
Md. Golam Mostafa
Md. Golam Mostafa 2016 年 11 月 20 日
Oh, sorry, I did not foresee the situation prevailing at your end. The command window showed the following:
Error using feof Invalid file identifier. Use fopen to generate a valid file identifier.
Error in multifileload (line 15) while feof(fileID)== 0;

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2016 年 11 月 20 日
fileID = fopen( fullfile(filesFolder, nameOfTextFiles{i}));
  1 件のコメント
Md. Golam Mostafa
Md. Golam Mostafa 2016 年 11 月 20 日
編集済み: Md. Golam Mostafa 2016 年 11 月 21 日
Thanks, it worked. I have 630 txt files. Can you suggest me easy way to store data in 630 different matrices?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by