Hi, i'm having trouble reading multiple excel files in a loop and performing simple calculation of the mean for a specific column

2 ビュー (過去 30 日間)
%Here is my code - I have three excel files named bec 1, bec 2, bec 3 saved to folder 'loop'. I want to calculate the mean of column 1(named 'potato') ,sheet1 in each file in a loop. I don't really need to store the data in an array but if anyone can help make this code work I would be very appreciative :).
cd('C:\Users\rebec\Desktop\loop')
numfiles=3
data=[];
for fileidx = 1:numfiles
filedata = readmatrix(sprintf('bec %d.xlsx',fileidx));
if fileidx == 1
data = zeros(size(filedata, 1), numfiles);
end
data(:, fileidx) = filedata.potato;
end
numfiles =
3
Dot indexing is not supported for variables of this type

採用された回答

Bhaskar R
Bhaskar R 2020 年 2 月 3 日
readtable is better than readmatrix here
folder_path = 'C:\Users\rebec\Desktop\loop'; % your path
num_files = 3; % number of excel files
data_mean = zeros(1, num_files); % initialize mean data with 0s
for ii =1:num_files
% form file name
file_name = fulfile(folder_path, sprintf('bec %d.xlsx',ii));
% read data from file
T = readtable(file_name, 'sheet', 'Sheet1');
% calculate mean and assign to data_mean
data_mean(ii) = mean(T.potato);
end
  1 件のコメント
rebecca wise
rebecca wise 2020 年 2 月 5 日
Thank you Bhaskar R. :) It worked and thank you so much for answering so quickly! Much appreciated X

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by