MATLAB: How to create new rows from numbers repeating themselves in two or more rows of a matrix

repeating values in matrix

Take for example matrix a:
a=[1 2 3 4; 5 8 10 1; 2 3 11 12].
Numbers recurring in different rows should create a new row and be emitted from the row they were in before, giving us the matrix:
a=[1 0 0; 2 3 0; 4 0 0; 5 8 10; 11 12 0]

Best Answer

This is not very easy, so why do you want to do that?
The following may do what you want:
a = num2cell(a, 2); %convert into a cell array of rows
height = numel(a);
result ={};
for row = 1:height;
for otherrow = row+1:height;
if isempty(a{row})
break;
end
[isfound, where] = ismember(a{row}, a{otherrow});
if any(isfound)
result = [result; a{row}(isfound)]; %#ok<AGROW>
a{row}(isfound) = []; %prevent extracted elements to be reprocessed
a{otherrow}(where(isfound)) = []; %remove duplicate
end
end
if ~isempty(a{row})
result = [result; a{row}]; %#ok<AGROW> append non-duplicate
end
end
Note that it puts non-recurring numbers after any recurring numbers in the same row.