MATLAB Answers

reading multiple excel files in matlab

21 views (last 30 days)
Matt on 10 Jul 2014
Answered: Geoff Hayes on 11 Jul 2014
I have multiple excel files at different folders. Lets say 10 excel files at 10 different folders. D:\1\1.xlsx.... to D:\10\10.xlsx!
I want to read the first column of each excel sheet and start it to ten variables in matlab. I am trying this, but didn't succeed. Can any one suggest me!
folder='D:\1\'; filetype='*1.xlsx'; f=fullfile(1,1); d=dir(f); for k=1:numel(d); data{k}=xlsread(fullfile(folder,d(k).xlsx)); end

Accepted Answer

Geoff Hayes
Geoff Hayes on 11 Jul 2014
Matt - You are pretty close to having the correct solution. The use of the cell array is a good idea for storing the data (as each column may have a different number of rows). It is just how to build the path to the file and its name that is (a little) tricky. Try the following
% there are 10 folders (or more, with assumption that directories and file are as
% you have described
n = 10;
% allocate slots in the cell array
data = cell(n,1);
% iterate
for k=1:n
% build the filename
filename = sprintf('D:\\%d\\%d.xlsx',k,k);
% read the first 100 rows of the first column
The only catch with the above is that your Excel files may have more than 100 rows. To get around this you could do the following within the above loop
% read the all raw (numeric and text) data from the file
[~,~,rawData] = xlsread(filename);
% save the first column of data
data{k} = rawData(:,1);
Type doc xlsread for details on this function. We use the tilde to ignore the first two outputs of numeric and text data) and get all raw data from the first worksheet of the file. Then we extract the first column and save it to the cell array.
Try the above and see what happens!

More Answers (0)

Community Treasure Hunt

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

Start Hunting!