Files
imdd_silas/Classes/DataBaseHandler/related functions/groupIt.m
Silas Oettinghaus 9ce23c4a10 Many changes in DBHandler
new general processing structure
just before splitting off the projects folder from this repo
2025-05-13 10:24:09 +02:00

53 lines
1.7 KiB
Matlab

function resultTable = groupIt(fixedVars, dataTable, aggregationFunction)
% groupIt Groups data in a table based on fixedVars and applies aggregationFunction to numeric data.
%
% resultTable = groupIt(fixedVars, dataTable, aggregationFunction)
%
% Inputs:
% fixedVars - Cell array of variable names to group by
% dataTable - Input MATLAB table
% aggregationFunction - Function handle (e.g., @mean, @min, @max)
%
% Output:
% resultTable - Grouped and aggregated table
[G, groupKeys] = findgroups(dataTable(:, fixedVars));
varNames = dataTable.Properties.VariableNames;
nVars = numel(varNames);
aggData = cell(height(groupKeys), nVars);
groupCount = zeros(height(groupKeys), 1);
for i = 1:height(groupKeys)
idx = (G == i);
groupCount(i) = sum(idx);
for j = 1:nVars
colData = dataTable.(varNames{j});
if isnumeric(colData)
if any(idx)
aggData{i, j} = aggregationFunction(colData(idx));
else
aggData{i, j} = NaN;
end
else
if iscell(colData)
nonEmptyIdx = find(idx & ~cellfun(@isempty, colData), 1);
if ~isempty(nonEmptyIdx)
aggData{i, j} = colData{nonEmptyIdx};
else
aggData{i, j} = [];
end
else
nonEmptyIdx = find(idx, 1);
if ~isempty(nonEmptyIdx)
aggData{i, j} = colData(nonEmptyIdx);
else
aggData{i, j} = [];
end
end
end
end
end
resultTable = cell2table(aggData, 'VariableNames', varNames);
resultTable.nRows = groupCount;
end