MATLAB: Looking for clever way to generate multiple submatrices.

forloopmatrixsubmatrix

I have a 2900 x 7 size matrix
re2 = [x y z se index xc yc]; Each dolumns -x, y, z, se, index, xc, yc- contains numbers, all 2900 x 1 same size.
Try to make some sub matrices from this one, by find specific elements in 6th & 7th column. such as
rexy_1_1 = re2(xc==1 & yc==1,:);
rexy_1_2 = re2(xc==1 & yc==2,:);
rexy_1_3 = re2(xc==1 & yc==3,:);
rexy_1_4 = re2(xc==1 & yc==4,:);
rexy_1_5 = re2(xc==1 & yc==5,:);
....
rexy_20_17 = re2(xc==20 & yc==17,:);
But this means I need to write 340 lines to generate 340 submatrices. Is there other clever way to do this? I tried to use two for loops, but not works. Need any help plz

Best Answer

[I,J]=ndgrid(1:20,1:17);
rexy=arrayfun(@(i,j) re2(re2(:,6)==i & re2(:,7)==j,:), I,J, 'uni',0);
%output will be a 20x17 cell array