Split matrix into unique bins, find max in each bin

Hi all, I have a question regarding splitting a matrix into unique bins, and then finding the absolute maximum in each bin.
My data looks like the following, except larger by several orders of magnitude:
-50 -51 -53 -50 -60 -68 -65 -40 -42 -48 -52
0 0 0 0 1 1 1 0 0 0 0
As you can see, I have two sequences of zeros, and one sequence of ones. What I find to write is something that returns the min and max values in each of these sequences ie. -53 and -50 for the first sequence, -60 and -68 for the second, and -40 and -52 for the third. I haven't been able to do this with just indexing commands yet. I have been thinking about splitting these into bins, where each sequence is marked with a unique flag, and then finding the min and max in each bin, but I'm not sure how to accomplish this either.

 Accepted Answer

One easy way would be to use cumsum and accumarray:
>> M = [-50,-51,-53,-50,-60,-68,-65,-40,-42,-48,-52;
0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0];
>> V = cumsum([1,diff(M(2,:))~=0]);
>> C = accumarray(V(:),(1:size(M,2)).',[],@(c){M(1,c)});
>> [cellfun(@min,C),cellfun(@max,C)]
ans =
-53 -50
-68 -60
-52 -40

2 Comments

cell2mat(accumarray(cumsum([true,diff(M(2,:)) ~= 0])',...
M(1,:)',[],@(x){[min(x),max(x)]}))
Thank you, Stephen, this works perfectly. I had no idea about those functions!

Sign in to comment.

More Answers (0)

Asked:

on 13 May 2017

Commented:

on 13 May 2017

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!