Compile mulitple csv files into one large table

1 次查看(过去 30 天)
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

回答(2 个)

dpb
dpb 2019-3-9
编辑:dpb 2019-3-9
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 个评论
ANNE NDJALI
ANNE NDJALI 2019-3-9
Thank you!
And, yes. I will use those two blank columns to have space to process the 5 columns of raw data.
dpb
dpb 2019-3-9
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
Walter Roberson 2019-3-9
% 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')

Community Treasure Hunt

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

Start Hunting!

Translated by