Hi George,
I understand that you intend to loop through an existing MATLAB Table and generate a new table with unique IDsalong with values as that of the sum of values associated with this ID, in the previous table.
To generate the desired table, you can use ‘varfun’ function that applies a function logic, using its specified handle, separately to each variable of the input table.
Here’s a brief code overview of a possible solution to this issue:
- Create the Original Table: Define the original table with your data.
T = table({'ID1'; 'ID1'; 'ID2'; 'ID1'}, [5; 7; 3; 1], 'VariableNames', {'ID', 'Value'})
T =
ID Value
_______ _____
{'ID1'} 5
{'ID1'} 7
{'ID2'} 3
{'ID1'} 1
- Group By ID and Sum Values: Use MATLAB function ‘varfun’ to group the data by ID and sum the Value for each ID.
G = varfun(@sum, T, 'GroupingVariables', 'ID', 'InputVariables', 'Value');
varfun(@sum, T, 'GroupingVariables', 'ID', 'InputVariables', 'Value'): groups the table by ID and computes the sum of the Value for each group. This function returns a new table where each row corresponds to a unique ID, and the Value column contains the sum of the values for that ID.
- Create the New Table: Construct the new table from the results.
NewTable = renamevars(G, 'sum_Value', 'Value');
disp(NewTable);
ID GroupCount Value
_______ __________ _____
{'ID1'} 3 13
{'ID2'} 1 3
‘renamevars’ is used to rename the ‘sum_Value’ variable to Value in the resulting table for consistency with the desired output.
For more information regarding usage of ‘varfun’ function in MATLAB, refer to the documentation link mentioned below:
https://www.mathworks.com/help/matlab/ref/table.varfun.html