MATLAB: MATLAB one-liners

discussionfunMATLABmatrix manipulation

One of the joys of using MATLAB is that it has a stock of matrix functions like diff, sort, all, and so on, that can be combined in all sorts of interesting ways. For example, in a recent question, the challenge was to find a compact code to determine which columns of a matrix A have all elements equal. Matt Tearle came up with this nifty answer:
all(~diff(A))
What are your favorite one-line MATLAB expressions?

Best Answer

cell2mat(arrayfun(@(K) accumarray(C, F(:,K), [], @mean), 1:size(F,2), 'Uniform', 0))
In response to a cssm question:
I have a feature matrix, F(m, n) and a cluster vector, C(m, 1).
Now I want to get the mean of feature in F according to C. Make
it simple as below:
F = [2 5; 3 7; 8 4]
C = [2; 1; 2]
output should be [3 7; (2+8)/2 (5+4)/2]
=[3 7; 5 4.5]
Related Question