How do i loop through a folder of excel files, perform a calculation from the data in each file, and then write the result of each calculation to a file?

3 views (last 30 days)
I have a folder of 100 excel files. Each file has 2 columns, column A is distance and column B is elevation. Each column has a variable length to it. I want to go through each file in my folder and calculate the slope of the data. Then I want to write the name of the file MATLAB just worked with to a new excel file along with the slope for each file. I am new to MATLAB so I would appreciate the help. My MATLAB script and excel data are saved to the same folder. The errors I have been getting include: 'Open method of Workbooks class failed' and 'Field reference for multiple structure elements that is followed by more reference blocks is an error.'
Here is the code I have so far:
source_dir= 'C:\Users\awhaling\Desktop\AW_elev';
dest_dir= 'C:\Users\awhaling\Desktop\AW_elev\slopes';
source_files = dir(fullfile(source_dir, '*.xls'));
len= length(source_files);
for i=1:len
data= xlsread(source_files(i).name);
x= data(:,1);
y= data(:,2);
mdl= fitlm(x,y);
slope= mdl.Coefficients(2,1);
xlswrite(fullfile(dstfile,'slope_data',slope));
end

Answers (1)

Walter Roberson
Walter Roberson on 14 Dec 2015
xlswrite(fullfile(dstfile,'slope_data'),slope);

Community Treasure Hunt

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

Start Hunting!