MATLAB: Find max and min of groups in columns of a matrix

findgrouping

I have a matrix with positive and negative values as:
a=[0 1;-3 3;-2 -7;0 5;4 -6;1 -2].
I would like to find by columns the maximum positive and minimum negative of each group of positive and negative values without any sorting. For the example given the result b would be:
b{1,1}= [-3;4]
b{1,2}= [3;-7;5;-6]
Thanks

Best Answer

a=[0 1;-3 3;-2 -7;0 5;4 -6;1 -2]
t = [true(1,size(a,2));diff(a<0)~=0];
ir = cumsum(t);
jj = max(ir);
ii = bsxfun(@plus,ir,[0,jj(1:end-1)]);
out1 = mat2cell(accumarray(ii(:),a(:),[],@(x)max(abs(x))*sign(sum(x))),jj,1);
out = cellfun(@(x)x(x~=0),out1,'un',0);