MATLAB: How to group and average non-sequential vectors

discretizegrpstatsMATLABtable

Given 2 long non-sequential vectors: X(t) and Y(t)
How can I:
1. Bin X(t) into different groups: [0-5), [5-10), [10-15), ….
2. Take average value of X(t) and Y(t) within each group
3. Plot the average value of Y_mean vs. X_mean

Best Answer

This workflow can be easily achieved when working with a table:
1. Using a sample data:
>> n = 500;
>> time = (1:n)';
>> X = 45*rand(n,1);
>> Y = 100*rand(n,1) + 10;
2. Store your data within a table:
>> T = table(time, X, Y);
3. Create a new categorical variable in the table which identify the grouping for each row using "discretize":
>> edges = (0:5:45)';
>> T.myGroup = discretize(T.X, edges,'categorical');
4. Now, you can get the mean of each group using "grpstats":
>> meanTable = grpstats(T, 'myGroup', 'mean');
>> meanTable.mean_time = []
5. and plot the mean:
>> figure
>> plot(meanTable.mean_X, meanTable.mean_Y)