Compile mulitple csv files into one large table
    5 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
I have 90 csv files, each with 5 columns of data. 
I need to read all 90 csv files into one large excel table, which pulls an additional 2 blank columns from each csv file (total of 7*90 columns wide).  
I have tried this code, which does not yet include anything for adding the extra 2 columns, and have been unsucessful in pulling data together. It pulls data from one of the csv files only and pulls the data in on different rows. 
% Read in data from Excel
source_dir = 'directory_name';
source_files = dir(fullfile(source_dir,'*.csv'))
% Import Data
for i = 1:length(source_files)
    Data = xlsread(fullfile(source_dir, source_files(i).name))  
end
xlswrite('file_i_want',Data,'tab_name')
Thank you for your help
0 comentarios
Respuestas (2)
  dpb
      
      
 el 9 de Mzo. de 2019
        
      Editada: dpb
      
      
 el 9 de Mzo. de 2019
  
      You're overwiting Data every iteration...
source_dir = 'directory_name';
source_files = dir(fullfile(source_dir,'*.csv'));
Data=[];
for i = 1:length(source_files)
  Data=[Data; xlsread(fullfile(source_dir, source_files(i).name))];
end
xlswrite('file_i_want',Data,'tab_name')
The above will work presuming all the data in the files is numeric.  xlsread is overhead-intensive, however, for ordinary text files.  I'd do something like
  Data=[Data; importdata(fullfile(source_dir, source_files(i).name))];
  instead, probably.  Adding columns is essentially trivial although I'd ask what's the point in having more columns than useful data until you have something to put there?
Data=[Data zeros(size(Data,1),2)];
2 comentarios
  dpb
      
      
 el 9 de Mzo. de 2019
				But those columns can be created dynamically by simple assignment of the result of the previous computations--you don't need to create empty space.
  Walter Roberson
      
      
 el 9 de Mzo. de 2019
        % Read in data from Excel
source_dir = 'directory_name';
source_files = dir(fullfile(source_dir,'*.csv'))
numfiles = length(source_files);
Data = cell(1, numfiles);
% Import Data
for i = 1:numfiles
    thisdata = xlsread(fullfile(source_dir, source_files(i).name));
    thisdata(:,6:7) = 0;    %or whatever is appropriate
    Data{1,i} = thisdata;
end
Data = [Data{:}]; %create one big numeric matrix    
xlswrite('file_i_want',Data,'tab_name')
Ver también
Categorías
				Más información sobre Spreadsheets en Help Center y File Exchange.
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!