MATLAB: Grouping repetead values in cells

MATLABrepeated values

Hi, I would like to group repeated values in a new matrix with four cells. As an simple example lets say that I have these two arrays (a,B) plus a new one (NewE) which is the matrix to my outputs:
a=[1;2;1;2]
NewB=cell(1,length(a))
B=[560800 x 20] %large numerical matrix where the first column contain the same values as in vector "a"
so I think to get the NewB in this simple form whitout using a counter:
for i = 1:length(B)
for j= 1: length(a)
if B(i,1) == a(j,1)
NewB{j}(end+1,:)=B(i,:);
end
end
end
It is obvious that the algoritm doesnt work but the idea was that.
Thank you for your help in advance,
/Fernando

Best Answer

If you want to are trying to separate the rows of matrix B on the basis of values in its column 1, then just use splitapply(),
NewB = splitapply(@(x) {x}, B, findgroups(B(:,1)))
NewB will have the same number of cells as the number of unique elements in B(:,1).
Edit: As stated by @Fernando, that the matrix must be divided into different portions according to the grouping of 1 and 2 in column 1. The following code will work in that case:
index = [0; find(diff(B(:,1))); 20];
portionSize = diff(fliplr(index));
dividedData = mat2cell(B, portionSize, size(B, 2));
you don't need to specify a separate a, the method split the matrix on the basis of consecutive portions in column 1.