MATLAB: Compare and group rows with remaining all rows of a matrix

comparing grouping rows of matrix

I want to group rows of matrix by lines. At the beginning, the line contains the first row of the matrix. This row is compared with the rest of the matrix; If condition = true, the other rows are added to that line and removed from the matrix. If condition = false, a new line is created. Taking the example below.
M2=[2093 1414 172 33;
1851 1416 147 31;
459 266 178 48;
189 268 175 46];
l=M2(1,:);
M2(1,:)=[];
while not(isempty(M2))
for i=1:numel(M2(:,4))
if l(1,4)-M2(i,4)<=5
l=[l;M2(i,:)];
M2(i,:)=[];
end
end
end
The result is:
l1=[2093 1414 172 33;
1851 1416 147 31]
l2=[459 266 178 48;
189 268 175 46];

Best Answer

Do not number variables. Use cell arrays that can easily be indexed instead:
M2 = [2093 1414 172 33;
1851 1416 147 31;
459 266 178 48;
189 268 175 46];
L = {}; %use cell array
while ~isempty(M2)
ismatch = abs(M2(1, 4) - M2(:, 4)) <= 5; %absolutely no need for a loop. do it for all the rows in one go
L{end+1} = M2(ismatch, :); %add matching rows as a new matrix at the end of the cell array
M2(ismatch, :) = [];
end
Related Question