有一组 excel 文件(10 个文件),每个文件都有一个表格:2 列(参数名称、参数值)和 12 行(参数数量及其值)。需要计算单个参数的 10 个变量之间的平均值。下面有一个程序可以实现此目的。但是,我注意到他执行计算时的误差为万分之一,他低估了它。例如,结果如下:
矩阵 | 使用 Excel 计算平均值 |
---|---|
0.0288 | 0,02891568 |
0.0008 | 0,000836121 |
0.0012 | 0,00117159 |
0.0723 | 0,07248086 |
0.0858 | 0,085798107 |
0.0867 | 0,086977032 |
0.1030 | 0,102957729 |
0.9524 | 0,959947104 |
-0.0050 | -0,005002288 |
0.0008 | 0,000837283 |
-0.0000 | -1,28168E-05 |
0.0000 | 2,17761E-06 |
clc, clear;
% Folder with Excel files
folder = 'The path to the folder with 10 excel files'; % the path to the folder
files = dir(fullfile(folder, '*.xlsx')); % we get a list of all excel files
% Initialize the vector to store the average values
average_values = [];
% Loop through all files
for i = 1:length(files)
% The full path to the file
file_path = fullfile(folder, files(i).name);
% Reading data from an Excel file
opts = detectImportOptions(file_path, 'VariableNamingRule', 'preserve');
data = readtable(file_path, opts);
% Check if there is at least one numeric column
if any(varfun(@isnumeric, data, 'OutputFormat', 'uniform'))
% We extract only numeric data
numeric_data = data{:, varfun(@isnumeric, data, 'OutputFormat', 'uniform')};
% We calculate the average values for the rows, ignoring NaN
avg_values_per_row = mean(numeric_data, 2, 'omitnan');
% Saving the average values in an array
average_values = avg_values_per_row;
else
warning('There are no numeric columns in the "%s" file.', files(i).name);
end
end
% Displaying average values
disp('Average values by line:');
disp(average_values);
% Displaying the number of rows
disp('Number of lines:');
disp(length(average_values));
如您所见,对于参数编号 1、4、6、8,低估值从 0.0001 到 0.0007 个单位(对于第 8 个参数,低估值已经是该数字的千分之一)。最有趣的是,如果您手动将每个参数的 10 个值输入mean
Matlab 中的函数并进行计算,它将给出正确的结果,而不会出现这种低估(使用第 8 个参数的示例):
>> mean([0.952380002 0.980380905 0.97087088 0.95237715 0.952379051 0.970871364 0.980383351 0.925921306 0.961536062 0.952370972
])
ans =
0.9599
代码中哪里可能存在问题以及如何修复它以便给出准确的结果?(附件包含一个带有示例文件的文件夹: https: //drive.google.com/file/d/1COPpBq2mU8Ww62DRvbOKTtr_aC-LsCIL/view? usp=sharing )