您已经注意到,在大多数情况下,复制代码行数十(更不用说数百或数千)次来做同样的事情可以(而且应该!)自动化。您正在做的是创建动态变量名称,which is bad, very bad,更不用说要求您复制粘贴同一行代码 50 次。相反,使用一个简单的循环读取所有文件。
还有其他几个较小的改进点,我将在下面的代码块中概述它们。
% First, select the directory where your files are
input_dir = "C:\path\to\your\folder";
% Read the entire directory, searching for files of your type
% change .txt to whatever file type you have.
file_list = dir([input_dir '\*.txt']);
% ROWS comes from the amount of rows in your table files
% Pre-allocate output arrays for memory efficiency
Temp = zeros(ROWS, numel(file_list));
p = zeros(ROWS, numel(file_list));
% Use a for loop, since you know how many elements there are
for idx = 1:numel(file_list)
% Read the files in order
tmp_data = readtable([input_dir file_list(idx).name)]);
Temp(:,idx) = mean([tmp_data .tempx(:), tmp_data .tempz(:)], 2)
p(idx,:) = mean([tmp_data .px(:), tmp_data .pz(:)], 2)
end
Temp 和 p 现在都是矩阵,您的原始 Temp_1 在 Temp(:,1) 中,p_1 在 p(:,1) 等中。这假设 Temp 和 p 是行,根据mean 中的维度参数。
您可能不得不考虑维度,因为我不知道您的数据大小。但总的来说,这应该为您提供一个很好的起点,让您了解如何使用预分配来读取多个文件并有效地存储它们。
请注意,虽然您可以使用while 循环,但鉴于您有固定的迭代次数,即文件数,没有太多需要。如果迭代次数不固定,我只会使用while 循环,例如在优化问题中,代码会根据达到某个条件而停止。
最后:MATLAB 有 great documentation 包括很多示例。如果您不了解某个功能,请前往那里作为第一个访问点。
祝你好运!