Compile mulitple csv files into one large table

조회 수: 2 (최근 30일)
ANNE NDJALI
ANNE NDJALI 2019년 3월 8일
댓글: dpb 2019년 3월 9일
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')

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by