Splitting a table using varagin
Show older comments
I have a table named data. I want to split it into three different tables based on variables in the first column. I implemented the following lines of code which work perfectly. However, I don't understand what the varagin function is doing. The matlab documentation states that the first term in the bracket after splittaply should be a function such as @max. Is varagin acting as some sort of function? Secondly, why is it written twice (@varagin and the varagin again).
Group = findgroups(Data{:, 1});
Split = splitapply( @(varargin) varargin, Data , Group);
3 Comments
Adam Danz
on 5 Dec 2021
This is really clever. Mind sharing where you saw this idea? I'll add an explanation below as an answer.
Doron Joffe
on 5 Dec 2021
Edited: Doron Joffe
on 5 Dec 2021
Note that keeping data together often makes it easier to analyze, e.g.:
Accepted Answer
More Answers (1)
The function definition in splitapply can also be an anonymous function in the form @(vars)func(vars) where vars can be a single or multiple variables and func is a function. But in this case, the anonymous function takes the form @(x)x which means that the function merely returns the input. varargin is an array of inputs.
Examples:
fun = @(x)x;
fun(pi)
fun2 = @(varargin)varargin;
fun2(1,2,'S')
splitapply splits variables within a table into groups and applies the specified function. Each variable (column) of a table is treated as a separate input variable so the splitapply function must have the same number of inputs as the number of table variables. varargin is a flexible way to accept all table variables without relying on knowing the table width.
The output for an nx3 table with 2 different groups would be a 2x3 cell array C where C{i,j} contains the values in table column j that correspond to group i.
1 Comment
Doron Joffe
on 6 Dec 2021
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!