MATLAB: Accumarray with custom std function

accumarrayfunctionMATLABstdsubs

Dear all,
I have an array of unsorted time values A(:,1) and corresponding displacements A(:,2). Example data attached. I want to sort those values and estimate their standard deviation, i.e.
accumarray(A(:,1),A(:,2),[],@std)
However, I want to do so by a somewhat customized std function where I can specify my own mean vector (which I have calculated from a larger set of data). So I wrote a new function which manually calculates the std by subtracting the specified mean vector. However, for it to work, I need to specify that for each 'subs' value (time value A(:,1) in this case) of accumarray I only use the specified row of my mean vector to perform the calculation. Is there a way to get access to accumarray 'subs' values to perform such operations?
PS I think I must use accumarray as I have rather large datasets, I have already solved this problem by the use of a for loop and found it to be considerably slower.
Thank you

Best Answer

For what you describe, I would probably proceed as follows, where u(i) is your "custom mean" on A(:,1)=i,
u=u(:); %ensure column vector
EX = accumarray(A(:,1),A(:,2),[],@mean);
EXsq = accumarray(A(:,1),A(:,2),[],@(x) mean(x.^2));
customStd = sqrt( EXsq - 2.*u.*EX + u.^2 );