MATLAB: Hi, I am trying to use grpstats on the program and trying to compute median and percentile and skew but somehow i am not getting the program to run.

errorgrpstatsmedianpercentileskewnesstime series

This is what I write
[ Z]= [WeekNum,C,E,G,I];
[stat1,stat2]= grpstats(Z,WeekNum,{'mean',@(Z) prctile(Z,50)})
This is the error I am getting—
Error using grpstats>tryeval (line 429) Error computing statistics for group '10'.
Error in grpstats (line 304) z(gnum,:,:) = tryeval(hfun,x(idx,:),glabel{gnum},tsize)';
Error in portfoliocharacterization (line 24) [stat1,stat2]= grpstats(Z,WeekNum,{'mean',@(Z) prctile(Z,50)}) Caused by: Function '@(Z)prctile(Z,50)' returned a result of size [1 1], expected size [1 5]. ————————————————————————
My data has 5 columns,containing financial statistics and I am grouping them based on what week they were calculated.
I would appreciate any help.

Best Answer

Rishav, I suspect the problem is that your data has a weeknum for which there is only one row. You'll need to specify 1 for the DIM argument to PRCTILE in your anonymous function. GRPSTATS tries to save time by evaluating the functions on all columns or a group of rows all at once, but when it hits the group with one row, PRCTILE without DIM computes along that row, not down the columns, and returns a scalar rather than a 1x5.
All of these summary stat functions have a DIM argument to control just this kind of edge case, it's usually a good idea to use them if the input can be a matrix. In this case, it's probably not obvious that GRPSTATS is passing a matrix to your function, but it is.
BTW, there is a median function, so you could have just used @(x)median(x,1).