MATLAB: How to extract labeled rows of a matrix

extraxtextraxt labeled rows from a matrixfor loopindexindexinglabeledmatrixrowssort

Hello Friends,
I have a matrix X of size NxD, where the Dth column is labeled. For example:
X = [1, 2, 3, Sunday
4, 5, 6, Monday
7, 8, 9, Sunday
10, 11, 12, Tuesday
13, 14, 15, Monday];
I want to extract the rows corresponding to each labels. So for above matrix, I should get the following matrices:
A = [ 1, 2, 3, Sunday
7, 8, 9, Sunday];
B = [4, 5, 6, Monday
13, 14, 15, Monday];
C = [10, 11, 12, Tuesday];
Here matrix A is of size 2xD, B is of size 2xD and C is of size 1xD.
I will appreciate any advise!

Best Answer

See if this does what you want:
X = {1, 2, 3, 'Sunday'
4, 5, 6, 'Monday'
7, 8, 9, 'Sunday'
10, 11, 12, 'Tuesday'
13, 14, 15, 'Monday'};
[UX,ia,ic] = unique(X(:,end), 'stable');
for k1 = 1:size(UX,1)
Out{k1} = X(k1==ic,:);
end
Out{1}
Out{2}
Out{3}
ans =
[1.0000e+000] [2.0000e+000] [3.0000e+000] 'Sunday'
[7.0000e+000] [8.0000e+000] [9.0000e+000] 'Sunday'
ans =
[ 4.0000e+000] [ 5.0000e+000] [ 6.0000e+000] 'Monday'
[13.0000e+000] [14.0000e+000] [15.0000e+000] 'Monday'
ans =
[10.0000e+000] [11.0000e+000] [12.0000e+000] 'Tuesday'