splitapply cumsum with non-scalar result

4 views (last 30 days)
I would like to be able to get the accumulating value of numbers from the first vector
>> t = [1 2 3 4 5; 0 0 2 2 2]'
t =
1 0
2 0
3 2
4 2
5 2
cumsum would work very well by writing cumsum(t(:,1)), however, if I wanted the second column to be a grouping value I haven't been able to work out how to write this. If I wanted the sum per group I could:
>> [G,results] = findgroups(t(:,2))
G =
1
1
2
2
2
results =
0
2
and then
>> splitapply(@(x) sum(x), t(:,1),G)
ans =
3
12
3) the thing is I would like to use cumsum in place of sum.
splitapply(@(x) cumsum(x), inputData,G)
Error using splitapply (line 132)
The function '@(x)cumsum(x)' returned a non-scalar value when applied to the 1st group of data.
To compute nonscalar values for each group, create an anonymous function to return each value in a scalar cell:
@(x){cumsum(x)}
I understand what the problem is, but I don't have enough experience to change the function to cater for the result being a non-scalar. I would be ever so grateful if anyone could help in this respect as I unfortunately haven't got much experience in MATLAB with this type of challenge but can see that it would be very useful to solve.
Thank you and kind regards,
William

Accepted Answer

Guillaume
Guillaume on 13 Feb 2019
The error message tells you exactly what to do:
splitapply(@(x){cumsum(x)}, inputData, G)
This will output a cell array, here each cell contains the cumsum of each group.
Note that in your sum example (and non-working cumsum) the anonymous function is not needed, you can pass directly a handle to sum or cumsum:
splitapply(@sum, t(:, 1), G)

More Answers (0)

Categories

Find more on Dialog Boxes 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!