Open multiple files from the same folder with fopen and textscan
    7 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
    Tessa Kol
 le 26 Août 2020
  
    
    
    
    
    Modifié(e) : Stephen23
      
      
 le 26 Août 2020
            In matlab I wrote the following code:
fid = fopen('LedgeTest_muSP_0.20_muRP_0.20.data.852','r');
% Read all the data from the file
dataRead = textscan(fid,'%f %f %f %f %f %f %f %f %f %f %f %f %f %f','HeaderLines',1);
expData = [dataRead{1}(:,1) dataRead{2}(:,1) dataRead{3}(:,1) dataRead{7}(:,1) dataRead{3}(:,1)+dataRead{7}(:,1) rhoPart*(4/3)*pi*(dataRead{7}(:,1).^3)];
Problem: How can I open en read multiple files from the same folder?
Problem example: All of the 5 .data files are located in the same folder together with the matlab code (see picture below)

In a for loop I want to extract the data from each .data file.
0 commentaires
Réponse acceptée
  Mohammad Sami
      
 le 26 Août 2020
        You can use a for loop to iterate over the files;
files = dir(fullfile(pwd,'*.data*'));
data = cell(length(files),1);
for i = 1:length(files)
    fid = fopen(fullfile(files(i).folder,files(i).name),'r');
% Read all the data from the file
    dataRead = textscan(fid,'%f %f %f %f %f %f %f %f %f %f %f %f %f %f','HeaderLines',1);
    data{i} = [dataRead{1}(:,1) dataRead{2}(:,1) dataRead{3}(:,1) dataRead{7}(:,1) dataRead{3}(:,1)+dataRead{7}(:,1) rhoPart*(4/3)*pi*(dataRead{7}(:,1).^3)];
end
alldata = vertcat(data{:});
0 commentaires
Plus de réponses (1)
  Stephen23
      
      
 le 26 Août 2020
        
      Modifié(e) : Stephen23
      
      
 le 26 Août 2020
  
      Following the examples in the documentation:
D = 'absolute or relative path to the folder where the files are saved';
S = dir(fullfile(D,'Ledge*.data.*'));
fmt = repmat('%f',1,14);
opt = {'HeaderLines',1, 'CollectOutput',true};
for k = 1:numel(S)
    fnm = fullfile(D,S(k).name);
    [fid,msg] = fopen(fnm,'rt');
    assert(fid>=3,msg)
    tmp = textscan(fid,fmt,opt{:});
    fclose(fid);
    mat = tmp{1};
    ... process mat data
    S(k).data = mat;
end
0 commentaires
Voir également
Catégories
				En savoir plus sur Data Import and Analysis dans Help Center et File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


