Averaging of rows from excel table

2 次查看(过去 30 天)
Hi! I have some excel data as shown in the picture. I would like to write a code where Matlab takes the average of the two rows that have both the same name and date and combines these two rows into one row with the value diaplayed as the average of the two combined values. I have highlighted in this example the two rows that have the same Name and Date with differing values. I have also included a picture of what the desired output would look like.
This is the input data
This is the desired output data.
Thank you!

采纳的回答

Ayush Anand
Ayush Anand 2024-4-16
Hi,
You can read the data into MATLAB using "readtable" and extract the unique combinations of "Name" and "Date" using the "unique" function. Iterating through the unique combination groups and averaging the values for each group should give you the desired answer. Here's how you can do the same:
% Read the Excel Data
filename = 'temp.xlsx'; % Specify your Excel file name
dataTable = readtable(filename);
% Converting 'Date' to datetime format:
dataTable.Date = datetime(dataTable.Date,'InputFormat','MM-dd-yyyy');
%Identify Unique Combinations of Name and Date
[uniqueGroups, ~, groupIndices] = unique(dataTable(:, {'Name', 'Date'}), 'rows');
% Average the Values for Each Unique Combination
% Initialize an array to store the averaged values
averagedValues = zeros(height(uniqueGroups), 1);
for i = 1:height(uniqueGroups)
% Find rows belonging to the current group
currentGroupRows = groupIndices == i;
% Calculate the average value for the current group
averagedValues(i) = mean(dataTable.Value(currentGroupRows));
end
% Create a New Table with Averaged Values
dateFormat = "MM-dd-yyyy";
resultTable = [uniqueGroups, table(averagedValues, 'VariableNames', {'AverageValue'})];
resultTable.Date = string(resultTable.Date, dateFormat);
% write the result to a new Excel file
outputFilename = 'averaged_data.xlsx';
writetable(resultTable, outputFilename);
Read more about the unique function here: https://www.mathworks.com/help/matlab/ref/double.unique.html

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Import from MATLAB 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by